Skip to main content

Overview

Playwright uses selector engines to find elements in the page. The selector system is highly flexible and supports multiple strategies.

Built-in Selector Engines

From server/selectors.ts:32-48:

CSS Selectors

Standard CSS selectors work out of the box:

CSS:Light

Pierces shadow DOM:

Text Selectors

Find elements by their text content:
Text selectors are normalized: trimmed and whitespace collapsed.

XPath Selectors

Role Selectors

Find elements by ARIA role (accessibility-first):
From utils/isomorphic/locatorUtils.ts:
Supported roles:
  • button, checkbox, radio, textbox
  • link, heading, img, list, listitem
  • table, row, cell, dialog
  • And all ARIA roles…

Test ID Selectors

Recommended for test automation:
HTML:
Use test IDs for stable, maintainable selectors that don’t break when styling changes.

Locator Methods

getByRole

getByText

getByLabel

getByPlaceholder

getByAltText

getByTitle

getByTestId

Combining Selectors

Chaining (>>)

Filtering with :has()

From client/locator.ts:44-70:

And Combinator

Or Combinator

React & Vue Selectors

Find elements by React/Vue component names:
React/Vue selectors require components to be in development mode or have displayName set.

Layout Selectors

Positional

Visibility

Filtering

Strict Mode

By default, actions require exactly one matching element:
Strict mode prevents accidental interactions with the wrong element.

Selector Examples

By Attribute

By Relationship

Complex Selectors

Custom Selector Engines

Register custom selector engines:

Selector Best Practices

Use roles, labels, and text that users see.
Add data-testid for elements without good text or role.
CSS and text selectors are more readable and maintainable.
Balance specificity with maintainability.

Debugging Selectors

Selector Performance

  1. CSS is fastest - Browser-native
  2. Text selectors are slower - Require content scanning
  3. XPath is slowest - Complex evaluation
  4. Layout selectors - May require style computation

Next Steps

Auto-waiting

How Playwright waits for elements

Locators

Locator API reference

Test Isolation

Ensuring independent tests