Locators are Playwright's primary way to find elements. They are strict, auto-waiting, and designed for user-facing queries rather than brittle CSS paths.
The Locator Model
A locator describes how to find element(s) on the page. Playwright re-evaluates locators before each action, so stale element references are rare compared to older WebDriver patterns.
Prefer user-facing locators (getByRole, getByLabel, getByText) over CSS/XPath. Use getByTestId when roles are ambiguous.
Actions require exactly one matching element by default. If zero or multiple match, Playwright throws with a helpful error listing candidates — fix locators instead of forcing .first() without reason.
Common Mistakes
CSS selectors tied to styling classes that change frequently.
Using .nth(3) when a role+name or filter would be stable.
Creating locators once before navigation and reusing after full page reload without re-querying.
XPath copied from DevTools when a role locator exists.
Key Takeaways
Locators are lazy and re-resolved before actions.
Prefer role, label, and test id over CSS.
Strict mode catches ambiguous selectors early.
Filter and chain to scope within tables and lists.
Pro Tip
Run npx playwright codegen on problematic pages — it suggests locators in priority order Playwright itself prefers.
Continue with getByRole to build on what you learned here.