Playwright Selectors
Learn how to use Playwright's powerful selector engine to locate elements on the page.
What are Selectors?
Selectors are used to identify and interact with elements on a web page. Playwright provides a rich set of selector types to help you target elements effectively.
Common Selector Types
1. CSS Selectors
CSS selectors locate elements using HTML attributes and structure.
await page.click('#loginButton');or
await page.fill('input[name="username"]', 'admin');CSS selectors are fast and commonly used in automation.
2. Text Selectors
Text selectors find elements based on their visible text content.
await page.click('text=Login');This clicks a button or link that contains the text Login.
Text selectors are useful when elements have clear visible labels.
3. Role Selectors (Accessibility)
Role selectors are based on accessibility roles used by screen readers.
They are recommended by Playwright because they are stable and user-focused.
await page.getByRole('button', { name: 'Login' }).click();4. XPath Selectors
XPath allows selecting elements using XML path expressions.
await page.click('//button[text()="Login"]');Although XPath works well, it is usually slower and harder to maintain compared to CSS selectors.
5. Test ID selectors
data-testid Best Practices.
Test ID selectors use custom data attributes to identify elements for testing purposes.
<button data-testid="login-btn">Login</button>Playwright can easily locate this element.
await page.getByTestId('login-btn').click();6. Chaining Selectors
Sometimes elements are nested inside other elements. Chaining selectors helps narrow the search.
await page.locator('#loginForm').locator('button').click();This first locates the form with id loginForm, then finds the button inside it.
7. Handling Dynamic Elements
Dynamic elements change attributes frequently, such as IDs or classes.
<button id="btn_12345">Submit</button>Since the ID changes, it is better to use a stable selector.
await page.getByRole('button', { name: 'Submit' }).click();Best Practices for Selectors
- Prefer role and text selectors for better readability
- Avoid overly specific CSS selectors that may break with UI changes
- Use data attributes (e.g.,
data-testid) for stable selectors in testing environments