🎯 Locator Strategies
Locator Strategies: A locator is a way to describe an element on the page — but not like a street address; more like an ISBN number in a library catalog: even if the book's cover
A locator is a way to describe an element on the page — but not like a street address; more like an ISBN number in a library catalog: even if the book's cover changes, its shelf moves, or the library relocates, the ISBN still finds the exact book because it references identity, not appearance. So if XPath and CSS selectors already exist, why does Playwright recommend role/text/testid instead? XPath and CSS selectors are tied to visual position or DOM hierarchy — if a developer swaps a div for a span or adds a wrapper layer, the locator breaks and the test ends up validating markup details rather than real user behavior. If you ever wrote By.xpath("//div[3]/span[2]/input") in Selenium/Java and the front-end team rearranged the page, tests went red even though nothing functionally changed — that's the "brittle test" problem. Playwright's getByRole("button", {name:"Buy Now"}) targets the interface as a screen reader sees it: it automatically covers accessibility testing for users with disabilities, and it's naturally resilient to DOM changes. The QA reality: if data-testid attributes are missing, the cheapest fix is talking to the dev team and planning testability at design time — before the brittleness compounds.
Locator Types — Selenium vs Playwright
Micro Lab: Playwright — Locator selection
Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.
Step by Step: Playwright — Locator selection
Try semantic locators first: getByRole, getByLabel, getByPlaceholder
If not semantic, use getByText or getByTestId
If CSS/XPath needed, write page.locator("css") or page.locator("xpath=...")
Verify locator works with await expect(locator).toBeVisible()
Narrow with filter()
If multiple elements match, narrow with .first() / .nth() / .filter()
What is the Playwright locator selection and verification order?
🎬 Same Refactor, Two Different Fates: CSS Locator vs Role Locator
CSS: "div > span > input"