Locators: find elements like a user
How Playwright finds an element: getByRole, getByLabel, getByText and getByTestId, why long CSS and XPath chains break, and the order to prefer.
Transcript
Before Playwright can click a button, it has to find it. That is a locator. A locator describes an element the way a user would: the button called Log in.
The best locator is get by role. A button, a link, a heading, plus its visible name. Next is get by label for form fields, and get by text for plain text on the page.
If an element has no good role or label, ask the developers to add a test I D. Then use get by test I D. It is stable, because it exists only for tests.
Avoid long C S S and X Path chains that follow the page layout. When a designer adds a banner or moves one box, the locator breaks, and the test fails for no real reason.
So use this order: role first, then label, then text, then test I D, and C S S only as a last resort. Your tests will survive redesigns.
Remember: describe elements the way a user sees them, and prefer role, label and test I D over layout.
More in this series
1:265Actions: click, fill, check and more
Every verb in a manual test case has a Playwright method: goto, click, fill, check, selectOption, hover, press and setInputFiles, and how Playwright acts like a real user.
1:256Assertions and auto-waiting
Write the expected result with expect, why fixed sleeps make tests slow and flaky, how Playwright waits automatically, and why web-first assertions retry.