Locators and Selectors
Relevant source files
The following files were used as context for generating this wiki page:
- CONTRIBUTING.md
- packages/playwright/types/test.d.ts
- packages/web/src/components/codeMirrorWrapper.spec.tsx
- tests/assets/wpt/accname/name/comp_tooltip.html
- tests/library/chromium/css-coverage.spec.ts
- tests/library/inspector/console-api.spec.ts
- tests/library/locator-generator.spec.ts
- tests/library/role-utils.spec.ts
- tests/library/selector-generator.spec.ts
- tests/library/selectors-register.spec.ts
- tests/page/locator-convenience.spec.ts
- tests/page/page-aria-snapshot.spec.ts
- tests/page/selectors-css.spec.ts
- tests/playwright-test/reporter-html.spec.ts
- tests/playwright-test/ui-mode-test-source.spec.ts
Locators are the central piece of Playwright's auto-waiting and retry-ability mechanism. They represent a way to find element(s) on the page at any moment. A locator is created with a selector string that describes how to find an element. The system supports a variety of selector engines, including standard CSS and XPath, as well as more robust, user-facing ones like ARIA roles, text content, and test IDs.
This document outlines the architecture and functionality of Playwright's locators and the underlying selector system. It covers how selectors are generated, parsed, and executed, with a focus on the built-in engines, locator API, and the accessibility-first approach that prioritizes user-visible attributes for creating resilient tests.
Architecture Overview
The locator and selector system in Playwright involves components on both the client-side (in the test script) and the browser-side (injected scripts).
The general flow for a locator action is as follows:
- A test script creates a
Locatorobject using methods likepage.getByRole()orpage.locator(). - This creates a selector string that encodes the query. For example,
page.getByText('Submit')becomesinternal:text="Submit"i. - When an action like
.click()is called on the locator, the selector string is sent to the browser. - An injected script in the page (
injectedScript) receives the selector string, parses it, and uses the appropriate selector engine to find the element(s) in the DOM. - The system performs actionability checks (e.g., visibility, enabled) before executing the action. If checks fail, it retries until the timeout is reached.
This diagram illustrates the high-level interaction:
Selector Engines
Playwright uses selector engines to query elements. It supports standard engines and defines its own for more robust selection.
Built-in Engines
css: For standard CSS selectors. This is the default if no engine is specified.xpath: For XPath 1.0 expressions.text: Finds elements based on their text content.id: Finds elements by theiridattribute.internal:*: A family of Playwright-specific engines for features likegetByRole,getByText, etc.
Custom Selector Engines
Playwright allows users to register their own selector engines using playwright.selectors.register(). This is useful for creating domain-specific selectors tailored to an application's structure.
A custom engine is an object with query and queryAll methods.
// Example of a simple custom engine registration
const createTagSelector = () => ({
query(root, selector) {
return root.querySelector(selector);
},
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
});
// In the test setup:
await playwright.selectors.register('tag', createTagSelector);
Sources: tests/library/selectors-register.spec.ts:15-23, 27
Engines can be registered to run in the main world or as a content script, which affects their execution context and what they can access.
Sources: tests/library/selectors-register.spec.ts:1-174
Locator Generation
Playwright's code generator and inspector aim to produce human-readable and resilient locators. The generation logic follows a specific priority order to find the best possible selector for a given element.
Generation Priority
The generator prioritizes selectors in the following order:
- Role-based locators:
getByRolewith an accessible name is preferred. - Test ID:
getByTestIdif adata-testid(or custom test ID attribute) is present. - Text content:
getByTextfor elements with unique text. - Labels:
getByLabelfor form controls associated with a<label>. - Placeholder:
getByPlaceholderfor inputs with placeholder text. - Alt text:
getByAltTextfor images. - Title:
getByTitlefor elements with atitleattribute. - CSS / XPath: As a fallback, it uses CSS selectors, potentially with
nth-childor other structural relations to ensure uniqueness.
This diagram shows the simplified decision flow for generating a selector:
The generator also performs optimizations, such as normalizing whitespace in text and shortening long text for readability.
Sources: tests/library/selector-generator.spec.ts:40-41, 61-64
Locator API
Playwright provides a rich Locator API to create and interact with element selectors.
getBy Locators
These are the recommended, high-level methods for creating locators.
| Method | Description | Example |
|---|---|---|
getByRole() | Locates elements by their explicit or implicit ARIA role, attributes, and accessible name. | page.getByRole('button', { name: 'Sign in' }) |
getByText() | Locates elements by the text they contain. Can be exact or a substring. | page.getByText('Welcome', { exact: true }) |
getByLabel() | Locates form controls by their associated label's text. | page.getByLabel('Password') |
getByPlaceholder() | Locates an input by its placeholder text. | page.getByPlaceholder('Enter your email') |
getByAltText() | Locates an element, usually an image, by its alt text. | page.getByAltText('Company logo') |
getByTitle() | Locates an element by its title attribute. | page.getByTitle('Close dialog') |
getByTestId() | Locates an element based on its data-testid attribute (configurable). | page.getByTestId('login-button') |
Sources: packages/playwright/types/test.d.ts:1300-1400, tests/library/locator-generator.spec.ts:25-150
Chaining and Filtering
Locators can be chained to narrow down the scope of the search. They can also be filtered to select elements that match certain criteria.
locator(selector): Narrows down the search to children of the current locator's element(s).filter(options): Filters the set of elements matched by the locator.hasText: Matches elements containing the given text.hasNotText: Matches elements not containing the given text.has: Matches elements containing a descendant that matches another locator.hasNot: Matches elements not containing a descendant that matches another locator.
and(locator): Intersects the locator with another, returning elements that match both.or(locator): Combines the locator with another, returning elements that match either.first,last,nth(index): Selects a specific element from the matched set.
Example of a complex chained locator:
// A section that has a div with a span, also has text "foo", and also has an 'a' tag.
const locator = page
.locator('section')
.filter({ has: page.locator('div').filter({ has: page.locator('span') }) })
.filter({ hasText: 'foo' })
.filter({ has: page.locator('a') });
Sources: tests/library/locator-generator.spec.ts:279-290, tests/library/inspector/console-api.spec.ts:68-86
Frame Locators
The frameLocator(selector) method creates a locator for an iframe, which can then be used to locate elements within that frame.
const frameLocator = page.frameLocator('#my-iframe');
const buttonInFrame = frameLocator.getByRole('button');
await buttonInFrame.click();
Sources: tests/library/locator-generator.spec.ts:310-323
ARIA Roles and Accessibility Name
Playwright's emphasis on getByRole is rooted in the principle that tests should reflect how users interact with the page. Accessible names and roles are what screen readers and other assistive technologies use, making them inherently more robust than brittle CSS or XPath selectors.
Accessible Name Computation
The accessible name of an element is calculated based on a priority order defined by the W3C AccName Specification. Playwright's implementation follows this standard.
The simplified computation flow is:
- Is
aria-labelledbypresent and valid? If so, use the text from the referenced elements. - Otherwise, is
aria-labelpresent and not empty? If so, use it. - Otherwise, fall back to other methods, such as:
- For form controls, the text of the associated
<label>. - For
<img>, thealtattribute. - For
<input type="button">, thevalueattribute. - For many elements, the text content of the element itself.
- The
titleattribute can also be used as a fallback in some cases.
- For form controls, the text of the associated
This hierarchy ensures that the most explicit and user-facing labels are preferred, leading to more stable tests. For example, even if the text inside a button changes, if it has a consistent aria-label, the test will not break.
Debugging with Console API
When a test is paused, Playwright exposes a playwright object in the browser's developer console. This object provides a set of utility functions to test and debug locators and selectors interactively.
| Console API Method | Description |
|---|---|
playwright.selector(element) | Generates a selector for the given DOM element. |
playwright.locator(selector, options) | Creates a locator and returns its matching element(s). |
playwright.getBy...(text, options) | The same getBy* methods available in the test script. |
playwright.$$(selector) | A shorthand for document.querySelectorAll, but works across shadow DOM boundaries. |
Sources: tests/library/inspector/console-api.spec.ts:50-112
Conclusion
Playwright's Locators and Selectors form a powerful system for identifying elements in a way that is resilient to DOM changes. By prioritizing user-facing attributes and accessibility roles, it encourages the creation of tests that are more aligned with user experience and less prone to breaking. The combination of a rich locator API, automatic selector generation, and powerful debugging tools provides a comprehensive solution for modern web automation.