Playwright Locators — 20 Real Examples (2026 Guide)
Every Playwright locator strategy explained with 20 real examples: getByRole, getByLabel, chaining, filtering, and the locator patterns senior SDETs prefer over XPath.

Last updated 2026-07-20 · 12 min read · By Avinash Kamble, reviewed by Priyanka G.
Locators are where 80% of Playwright test debt lives. Get them right and the suite stays green through 6 months of UI refactors; get them wrong and every sprint costs a day of maintenance. This is the locator playbook we use across 5,000+ tests in production.
Key takeaways
- The 5 built-in locator strategies ranked by resilience.
- 20 worked examples across forms, tables, modals, and iframes.
- When to use filter() vs nth() vs chaining.
- Why getByRole beats XPath in 95% of cases.
1. The priority order Playwright recommends
page.getByRole()— accessibility-first, resilient to DOM changes.page.getByLabel()— for form fields.page.getByPlaceholder()— when no label exists.page.getByText()— for buttons and links with unique copy.page.getByTestId()— last resort, when semantic queries fail.
Only fall back to CSS or XPath for third-party widgets you cannot instrument. See the official locators reference.
2. Ten basic examples
// 1. Button by role + name
await page.getByRole('button', { name: 'Sign in' }).click();
// 2. Form field by label
await page.getByLabel('Email').fill('a@b.com');
// 3. Link
await page.getByRole('link', { name: 'Pricing' }).click();
// 4. Checkbox
await page.getByRole('checkbox', { name: 'I agree' }).check();
// 5. Select option
await page.getByLabel('Country').selectOption('India');
// 6. Radio
await page.getByRole('radio', { name: 'Monthly' }).check();
// 7. Text (exact)
await page.getByText('Welcome back', { exact: true }).waitFor();
// 8. Placeholder
await page.getByPlaceholder('Search products').fill('shoes');
// 9. Alt text (image)
await page.getByAltText('Company logo').click();
// 10. Test id
await page.getByTestId('cart-count').should('have.text', '3');3. Ten advanced examples — filter, chain, iframe
// 11. Filter a list by text
await page.getByRole('listitem').filter({ hasText: 'Product A' }).click();
// 12. Chain within a card
await page.getByRole('article', { name: 'Order 4211' })
.getByRole('button', { name: 'Cancel' }).click();
// 13. Nth (avoid if possible)
await page.getByRole('row').nth(2).click();
// 14. Combine has and hasNot
await page.getByRole('row').filter({ hasNot: page.getByText('Delivered') });
// 15. Iframe
await page.frameLocator('#stripe').getByLabel('Card number').fill('4242 ...');
// 16. Shadow DOM (built-in support)
await page.getByRole('button', { name: 'Open' }).click();
// 17. Regex text
await page.getByText(/order #\d+/i).click();
// 18. Wait for locator
await page.getByText('Loaded').waitFor({ state: 'visible' });
// 19. Assert count
await expect(page.getByRole('row')).toHaveCount(10);
// 20. Screenshot a single element
await page.getByRole('article', { name: 'Order 4211' }).screenshot({ path: 'card.png' });4. Anti-patterns to avoid
page.locator('xpath=//div[3]/span[2]')— positional XPath dies on any refactor.- CSS with generated class names (
.css-abc123) — Tailwind and CSS-in-JS make these unstable. - Chaining
.nth(0)instead of.first()— less readable. - Missing
awaitbefore an action — silent race condition.
Compare against Selenium's locator model to see why Playwright's role-based approach is more maintainable.
Frequently asked questions
1.Should I still use CSS selectors in Playwright?
2.Is getByTestId better than getByRole?
3.How do I locate shadow DOM elements?
4.Can I use XPath for iframe elements?
Practice these questions
Drill 200+ Playwright questions with senior-SDET sample answers — locators, auto-wait, fixtures, parallelism and trace viewer.
Was this article helpful?
More from Playwright TypeScript
Playwright with TypeScript — POM, fixtures, locators.
- Automation TestingPlaywright Locator Best Practices (2026) — The Only Guide You Need
- Automation TestingPlaywright Framework Setup with TypeScript: Complete 2026 Guide for QA Engineers
- Automation TestingPlaywright TypeScript Tutorial: Complete 2026 Guide
Keep building your QA edge
Pillar guides- Selenium PillarSelenium WebDriver guide300 Selenium WebDriver Q&A — locators, waits, frameworks.
- Playwright Installation GuideSoftwareTestPilot's Playwright installation walkthroughInstall Playwright the right way — Node, browsers, VS Code, first test.
- XPath & CSS Selector Generatorgenerate locators from any HTML snippetInteractive locator generator for Playwright, Selenium and Cypress — with Page Object export.
- Automation QA Engineer RoleAutomation QA Engineer career guideAutomation QA Engineer job scope, tools, salary, and hiring pipeline.
- QA Skills HubSoftwareTestPilot's QA skills tracksStructured skill tracks — Selenium, Playwright, Cypress, API, JMeter, SQL, Java, Python for testers.
- QA Practice Hubpractise on real sample appsHands-on labs — Selenium, Playwright, API, SQL exercises with sample apps and solution walkthroughs.
Practice these questions live
Rehearse with an AI QA interviewer that scores your answers in real time.
Continue reading

Playwright Locator Best Practices (2026) — The Only Guide You Need
11 min read
How to Migrate a Postman Collection to Playwright API Tests (2026 Guide)
12 min read
Why Every QA Engineer Must Master CI/CD Pipelines in 2026 (Or Risk Obsolescence)
12 min readRelated concepts, tools & standards around Automation Testing
A quick reference of the people, companies, frameworks and technologies most often mentioned alongside Automation Testing in real QA teams — useful when you're mapping a learning path, preparing for interviews, or scoping a new project.
Join the QA Community
Connect with fellow testers, share job leads, and get career advice.
Stop Reinventing the Wheel. Upgrade Your QA Arsenal.
Take your testing skills from beginner to Lead Engineer. Supercharge your daily workflow with our premium digital resources.
- Ready-to-use testing strategy templates
- Advanced API & UI automation guides
- ⏱️ Save 10+ hours a week on test planning
Discussion
Ask a question, share your experience, or correct us. Be kind — real people are reading.