Playwright Locators Cheat Sheet

In traditional automation tools like Selenium, we mostly use IDs, CSS selectors, and XPath to locate elements in a web application. Playwright supports all of these selectors as well, but it also provides powerful built-in locator methods that make tests more readable, stable, and user-focused.

All locators listed below auto-wait until the element is visible and actionable (ready to click, type, etc.), so you usually don’t need explicit waits.
 

Locator Methods

Example

Use Case

page.getByText(text)

const el = page.getByText('Login');

Finds an element containing visible text. Best for links, buttons, and labels.

page.getByRole(role, { name })

const btn = page.getByRole('button', { name: 'Submit' });

Finds elements using ARIA role and accessible name. Most recommended for stable and accessible tests.

page.getByLabel(label)

const input = page.getByLabel('Username');

Finds form controls associated with a

page.getByPlaceholder(placeholder)

const search = page.getByPlaceholder('Search...');

Finds inputs using the placeholder attribute.

page.getByTitle(title)

const help = page.getByTitle('Help');

Finds elements using the title attribute (tooltips, icons).

page.getByTestId(id)

const card = page.getByTestId('user-card');

Finds elements using test IDs like data-testid. Useful when no stable text or role exists.

page.locator(selector)

const el = page.locator('#main .item');

Generic locator using CSS, ID, or XPath. Use when other locators are not suitable.

locator.nth(index)

const second = page.locator('.row').nth(1);

Selects the element at a specific index (0-based).

locator.first() / locator.last()

const first = page.locator('.menu').first();

Selects the first or last matching element.

locator.filter({ hasText })

const item = page.locator('.card').filter({ hasText: 'Active' });

Narrows down elements based on inner text.

Chaining locators

const submitInForm = page.locator('#form').getByRole('button', { name: 'Submit' });

Scopes a search inside a parent element for better accuracy.

 

Locator Tips

     - Prefer getByRole, getByLabel, and getByText for better accessibility and stability.
     - Avoid brittle CSS or XPath selectors that depend on layout or styling classes.
     - Locators are auto-waiting and retryable, so store them in variables and reuse them safely.

 

Related Tutorials