Locators: find elements like a user

Knowledge Videos

Short animated explainers, organised by subject.

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