Understanding Locator Strategies in Playwright
Choosing locators: role, text, label, placeholder, test id, and CSS.
Locators are used to identify elements on a web page so that Playwright can interact with them or verify their state.
1. Common Locator Strategies
Role-Based Locators (Recommended)
Identify elements using their ARIA role and accessible name.
page.getByRole('button', { name: 'Login' });
page.getByRole('link', { name: 'Home' });
page.getByRole('textbox', { name: 'Email' });
Text-Based Locators
Locate elements using their visible text.
page.getByText('Welcome');
page.getByText('Add to Cart');
Test ID Locators
Use dedicated testing attributes such as data-testid.
<button data-testid="submit-button">Submit</button>
page.getByTestId('submit-button');
Label-Based Locators
Identify form controls using their associated labels.
page.getByLabel('Email');
page.getByLabel('Password');
Placeholder-Based Locators
Locate input fields using their placeholder text.
page.getByPlaceholder('Enter your email');
page.getByPlaceholder('Search products');
CSS Selectors
Select elements using IDs, classes, attributes, or relationships in the DOM.
page.locator('#username');
page.locator('.submit-button');
page.locator('[data-status="active"]');
2. Using Locators for Interactions
Locators can be used with actions and assertions.
// Fill an input
await page.getByLabel('Email').fill('[email protected]');
// Click a button
await page.getByRole('button', { name: 'Login' }).click();
// Verify an element is visible
await expect(
page.getByRole('heading', { name: 'Dashboard' })
).toBeVisible();
3. Best Practices
- Prefer user-facing locators: Use
getByRole(),getByLabel(), andgetByText()when appropriate. - Use test IDs when necessary: Prefer stable, dedicated testing attributes when accessible names are insufficient or ambiguous.
- Avoid brittle selectors: Avoid long CSS selectors that depend on the exact DOM hierarchy or frequently changing classes.
- Be specific: Ensure a locator uniquely identifies the intended element.
- Use assertions: Verify the expected state instead of assuming an action succeeded.
4. Quick Reference
| Locator | Use case |
|---|---|
getByRole() |
Buttons, links, headings, form controls |
getByText() |
Visible text content |
getByLabel() |
Form fields with labels |
getByPlaceholder() |
Inputs with placeholders |
getByTestId() |
Elements with dedicated test IDs |
locator() |
CSS selectors and other supported selector strategies |
Best practice: Prefer role-based and label-based locators for user-facing elements, use test IDs for stable identification when needed, and reserve CSS selectors for cases where other locator strategies are unsuitable.