All challenges · Guide
Playwright locators tutorial: write locators that don’t break
Written by Babatunde, test automation engineer · Last updated · Playwright 1.59.1
This Playwright locators tutorial is for testers who want locators that still work after the page changes. You will learn Playwright’s built-in locators, when to use each one, and how to narrow a match without a fragile CSS path. After each type, practise on a real Locator League challenge: a hidden check marks your answer and there is nothing to install.
All 30 challenges are free. Challenges 1 to 10 work without an account; a free account (no card) opens 11 to 30.
A locator finds an element at the moment you use it, not as a one-off snapshot of the page. Each time you click, fill or assert, Playwright looks the element up again and waits until it is ready. Official docs: Playwright locators.
Try each locator as you read. Type one below, or pick an example, and every element it matches on the sample page is outlined and numbered. Two or more matches is what Playwright calls a strict mode violation.
LOCATOR SANDBOX
Try it now · runs in your browser · not scoredWhich locator should I use?
Playwright recommends user-facing attributes and explicit contracts, with page.getByRole() first. Use this order unless you have a clear reason not to:
getByRole: the role and accessible name that users and assistive technology perceive (a button named “Sign in”, a heading named “Sign up”).getByLabel: a form control from its associated label,aria-labelledbyoraria-label.getByPlaceholder: only when the field has a placeholder and no proper label.getByText: non-interactive text, such as a welcome message or a validation error.getByAltText: an image, or another element, by its text alternative.getByTitle: when thetitleattribute is the only stable hook.getByTestId: when your team has agreed an explicit test-id contract. It survives copy and role changes, but it is not user-facing.- CSS or XPath with
page.locator(): only when you must. These often break when the page structure changes.
Most of these locators accept { exact: true } for a case-sensitive, whole-string match. The default is false, and the option is ignored for a regular expression. Exact matching still trims whitespace. For getByRole, exact applies to the name option; without it, name matching is case-insensitive and looks for a substring.
If more than one element matches, filter or chain until the locator is unique. Do not jump straight to nth().
Locate by role: getByRole
page.getByRole() is the locator Playwright recommends first. It uses the element’s explicit or implicit ARIA role, and usually an accessible name. Many HTML elements already have an implicit role: button, a with an href (link), h1 to h6 (heading), a native checkbox, a native <select> (combobox) and a number input (spinbutton).
Pass the accessible name in the name option. It can be a regular expression, and you can also filter by states such as checked or disabled, or by heading level.
await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
await page.getByRole('checkbox', { name: 'Subscribe' }).check();
await page.getByRole('button', { name: /submit/i }).click();Practise it: Click a Button: find a control the way a user does, by its role and visible name, and act on it.
Also useful: Follow a Navigation Link, Interact with Checkboxes, Fill a Number Input, Select from a Dropdown and Accessibility Assertions (Full Authoring).
Locate by label: getByLabel
Most form controls should have a label. page.getByLabel() finds the control from the associated <label> text, from aria-labelledby, or from aria-label. That is usually more stable than the input’s id or a CSS class, because the label is what a user reads.
await page.getByLabel('Postcode').fill('SW1A 1AA');
await page.getByLabel('House number').fill('10');
await page.getByRole('button', { name: 'Find address' }).click();Practise it: Fill a Login Form: fill a username and password through their labels and submit the form, as a user would.
Locate by placeholder: getByPlaceholder
page.getByPlaceholder() finds an input by its placeholder text. Placeholders are hints, not labels, and they disappear once the user types, so prefer getByLabel when a label exists.
await page.getByPlaceholder('name@example.com').fill('ada@example.com');Practise it: Add a Todo Item: fill a field and send a key to it as two separate actions.
Locate by text: getByText
page.getByText() finds an element by the text it contains. You can pass a substring (the default), an exact string, or a regular expression. It is a good fit for messages and other non-interactive text. For a button or a link, getByRole with a name is usually clearer. Inputs of type button or submit are matched by their value, not by text content.
await expect(page.getByText('Welcome, Ada')).toBeVisible();
await expect(page.getByText('Welcome, Ada', { exact: true })).toBeVisible();
await expect(page.getByText(/welcome, [a-z]+$/i)).toBeVisible();Practise it: Test Form Error Messages: submit a form with wrong details on purpose, and let the hidden check confirm the page shows the right error.
Locate by alt text: getByAltText
Images should have an alt attribute that describes them. page.getByAltText() finds an element, usually an image, by that text alternative.
await page.getByAltText('Company logo').click();Practise it: Reveal Hidden Content on Hover: some content appears only when the pointer is over an element. Find the right image by its alternative text.
Locate by title: getByTitle
page.getByTitle() finds an element by its title attribute. A title often appears only as a tooltip, so this sits below role, label and visible text. Use it when that attribute is the stable contract you have.
await expect(page.getByTitle('Open issues')).toHaveText('25 issues');Locator League does not have a dedicated getByTitle challenge yet. Keep practising user-facing locators in the challenge list.
Locate by test id: getByTestId
page.getByTestId() finds an element by a test id. The default attribute is data-testid. You can change it with testIdAttribute in the Playwright config, or at runtime with selectors.setTestIdAttribute().
Playwright describes test ids as a resilient contract: the test still passes if the visible text or role changes. The trade-off is that you are no longer testing what a user perceives. If the test should prove a user can find the control, prefer getByRole or getByLabel.
await page.getByTestId('directions').click();Locator League does not have a dedicated getByTestId challenge yet.
CSS and XPath: page.locator()
If you must use CSS or XPath, create a locator with page.locator(). Playwright accepts both, and detects which one you mean if you leave out the css= or xpath= prefix.
await page.locator('css=button').click();
await page.locator('xpath=//button').click();
await page.locator('button').click();
await page.locator('//button').click();Long CSS or XPath chains that walk the page structure, especially paths full of nth-child and generated class names, break when a wrapper is added or a class is renamed, even if the control still looks the same to a user. XPath also does not pierce shadow roots. Prefer a role, label or test-id locator.
Practise it: Debug the Broken Test (Full Authoring): you get a broken test with several bugs. Find and fix them, then write the assertions yourself.
Filter, chain, and first / last / nth
The getBy… methods exist on Locator and FrameLocator as well as on Page, so you can narrow the search in steps. locator.filter() keeps only the matches that fit extra criteria:
hasText/hasNotText: match or exclude text somewhere inside the element, including in a descendant, case-insensitively. A regular expression also works.has/hasNot: keep elements that do or do not contain a descendant matching another locator. That inner locator is resolved from each match, not from the document root.visible: keep only visible, or only hidden, elements.
const order = page.getByRole('listitem').filter({ hasText: 'Order #1042' });
await order.getByRole('button', { name: 'Track parcel' }).click();You can also combine locators with locator.and() and locator.or().
locator.first(), locator.last() and locator.nth() pick one match by position. Playwright does not recommend them as a first choice: if the page order changes, you act on the wrong element. Use them when position is the only difference.
const secondResult = page.getByRole('article').nth(1); // 0-based: the second oneFor elements inside an iframe, scope first with frameLocator, then chain a getBy… locator into that frame.
Practise it: Filter Table Rows: narrow a locator to one table row by its text, then act on a control inside that row. For frames, see Interact Inside an iFrame.
Strict mode and common mistakes
Locators are strict. An action that needs one target, such as click() or fill(), throws if more than one element matches. Operations meant for a set of elements, such as count(), are fine when several match.
// Throws if the page has more than one button
await page.getByRole('button').click();
// Fine: this works on all matches
const buttons = await page.getByRole('button').count();You can keep a locator in a variable and use it many times. It is not a saved element: each action looks it up again. Practise this in Count Multiple Elements.
A strict mode error means the locator is too broad. Tighten it with a name, a label or a filter. first(), last() and nth() avoid the error by picking one match, so keep them as a last resort.
Common mistakes:
- Matching twice with a substring.
getByRole('button', { name: 'New' })matches both “New” and “New email” unless you setexact: trueor tighten the name. - Using a CSS class or a generated id. These often change in the next build.
- Calling
nth(0)to silence a strict mode error instead of writing a unique locator. - Sleeping with
waitForTimeout. Locators already retry and auto-wait. A fixed delay makes tests slow and still flaky. Practise this in Wait for Dynamic Content and Fix the Flaky Test. - Forgetting that
getByTextnormalises whitespace. Even withexact: true, several spaces become one and line breaks become spaces.
FAQ
What is the difference between a locator and a CSS selector?
A CSS or XPath selector describes a path through the page. A Playwright locator runs its search again each time you use it, waits for the element to be ready and, for single-element actions, insists on a unique match. page.locator('button') still gives you a locator, but getByRole('button', { name: 'Save' }) usually survives markup changes better.
Why do I get a strict mode violation?
The locator matched more than one element, and the method you called needs exactly one. Add the accessible name, filter by text, or scope the search to one section of the page. Try those before nth().
Should I learn getByRole before the other locators?
Yes, if you are new to Playwright. Role locators cover buttons, links, headings, checkboxes and text fields, and they are the style Playwright recommends. Start with Click a Button, then come back for labels, text and filters.
When should I use getByTestId instead of getByRole?
When the visible name is unstable, when there is no useful role or label, or when your team has agreed test ids as the contract. If the test should prove that a user can find and use the control, prefer getByRole or getByLabel.
Where can I practise Playwright locators online for free?
On Locator League: 30 free challenges you run in the browser, with automatic checks and no local setup. For a guided order, follow a learning path: From Manual Testing to Playwright or Playwright Interview Practice.
Try it
Write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. The reference solution is shown only after you pass.