Resilient Locator Strategies
Intermediatev1.0.0
Master Playwright's locator API — choose the right selector strategy for each element using getByRole, getByLabel, getByText, and getByTestId in the correct priority order.
Content
Overview
Playwright's locator API is designed to find elements the way users and assistive technology see them. Choosing the right locator strategy makes tests resilient to refactors, readable by non-developers, and inherently accessible.
The Locator Priority Pyramid
Tier 1: Semantic (Preferred)
Tier 2: Label-Based
Tier 3: Test ID (Last Resort)
Avoid: CSS/XPath
Filtering and Chaining
Handling Dynamic Content
Best Practices
- -Start with
getByRole— it guarantees accessibility and resilience - -Use
getByLabelfor form inputs — it validates label associations - -Use exact matching when text could be ambiguous:
{ exact: true } - -Chain locators to scope within specific sections (navigation, main, footer)
- -Use regex for dynamic content instead of partial string matching
Common Mistakes
- -Reaching for CSS selectors first (habit from jQuery/Selenium era)
- -Using
page.locator()with CSS whengetByRole()works - -Not scoping locators — getting the wrong button on a page with multiple
- -Using
waitForSelectorinstead ofexpect().toBeVisible() - -Hardcoding text that changes with i18n or A/B tests
FAQ
Discussion
Loading comments...