Answer
What are Locators in Playwright?
Locators are strict, auto-retrying element selectors in Playwright. Unlike page.$() which returns a static element handle, locators represent a way to find elements and retry automatically when the element is not yet available.
Types of Locators
1. Role Locator (Most Recommended)
Uses ARIA roles — the most accessible and resilient locator.
page.getByRole('button', { name: 'Submit' })
page.getByRole('textbox', { name: 'Email' })
page.getByRole('link', { name: 'Sign in' })
page.getByRole('checkbox', { name: 'Remember me' })
page.getByRole('heading', { name: 'Dashboard' })
2. Text Locator
Locate by visible text content.
page.getByText('Welcome back')
page.getByText('Terms and Conditions', { exact: true })
3. Label Locator
Locate form fields by their associated label text.
page.getByLabel('Email address')
page.getByLabel('Password')
4. Placeholder Locator
Locate inputs by placeholder text.
page.getByPlaceholder('Enter your email')
page.getByPlaceholder('Search...')
5. Alt Text Locator
Locate images by alt attribute.
page.getByAltText('Company logo')
6. Title Locator
Locate by title attribute (tooltips).
page.getByTitle('Close dialog')
7. Test ID Locator (Best for Teams)
Locate by data-testid attribute — decoupled from UI implementation.
page.getByTestId('login-button')
page.getByTestId('user-email-input')
<button data-testid="login-button">Login</button>8. CSS Selector
Traditional CSS selectors.
page.locator('#username')
page.locator('.btn-primary')
page.locator('input[type="email"]')
9. XPath
XPath expressions.
page.locator('//button[text()="Submit"]')
page.locator('xpath=//div[@class="container"]')
Locator Best Practice Priority
getByRole() → Best (accessible, resilient)
getByLabel() → Great for form fields
getByText() → Good for visible text
getByTestId() → Best for teams (requires dev cooperation)
CSS Selector → Acceptable
XPath → Last resort
Key Locator Methods
await locator.click()
await locator.fill('text')
await locator.check()
await locator.selectOption('value')
await locator.waitFor()
await expect(locator).toBeVisible()
const count = await locator.count()
const text = await locator.textContent()
