</>

Technology

Playwright

Difficulty

Beginner

Interview Question

What are locators in Playwright and what types are available?

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.

TypeScript
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.

TypeScript
page.getByText('Welcome back')
page.getByText('Terms and Conditions', { exact: true })

3. Label Locator

Locate form fields by their associated label text.

TypeScript
page.getByLabel('Email address')
page.getByLabel('Password')

4. Placeholder Locator

Locate inputs by placeholder text.

TypeScript
page.getByPlaceholder('Enter your email')
page.getByPlaceholder('Search...')

5. Alt Text Locator

Locate images by alt attribute.

TypeScript
page.getByAltText('Company logo')

6. Title Locator

Locate by title attribute (tooltips).

TypeScript
page.getByTitle('Close dialog')

7. Test ID Locator (Best for Teams)

Locate by data-testid attribute — decoupled from UI implementation.

TypeScript
page.getByTestId('login-button')
page.getByTestId('user-email-input')
HTML: <button data-testid="login-button">Login</button>

8. CSS Selector

Traditional CSS selectors.

TypeScript
page.locator('#username')
page.locator('.btn-primary')
page.locator('input[type="email"]')

9. XPath

XPath expressions.

TypeScript
page.locator('//button[text()="Submit"]')
page.locator('xpath=//div[@class="container"]')

Locator Best Practice Priority

CODE
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

TypeScript
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()

Follow AutomateQA

Related Topics