Playwright Locators
A locator describes how Playwright finds an element. It should be readable, stable and based on user-visible behavior where possible.
What are locators?
const submitButton = page.getByRole('button', {name: 'Submit'});
await submitButton.click();
Locators do not immediately retrieve an element in every case. They are resolved when an action or assertion evaluates them.
getByRole
Role locators reflect semantic accessibility behavior.
await page.getByRole('textbox', {name: 'Email'}).fill('tester@example.com');
await page.getByRole('button', {name: 'Sign in'}).click();
getByText
Text locators are useful for visible text or status messages.
await expect(page.getByText('Login successful')).toBeVisible();
getByLabel
Use labels for form controls with accessible names.
await page.getByLabel('Password').fill('Secret123!');
CSS and XPath
CSS is appropriate for stable attributes, layout-adjacent elements or custom components.
await page.locator('[data-testid="cart-count"]').click();
XPath should be a later choice because it can become brittle when markup changes.
Real-world example
test('submits a valid support request', async ({page}) => {
await page.goto('/support');
await page.getByLabel('Subject').fill('Login issue');
await page.getByLabel('Description').fill('Unable to access my account');
await page.getByRole('button', {name: 'Submit request'}).click();
await expect(page.getByText('Request submitted')).toBeVisible();
});
Common mistakes
- Selecting elements with deeply nested CSS paths.
- Using text that changes with translations.
- Using
first()to hide an ambiguity problem. - Locating an element by implementation data when a role or label is available.
- Clicking before an element is ready instead of using web-first assertions.
Summary
- Locators find elements lazily and support Playwright actions and assertions.
- Accessibility-based locators are usually the most stable.
- Strict locators expose ambiguous matches instead of silently selecting the wrong element.
- Test IDs are useful for stable application controls.