Playwright Locators: Complete Guide With Examples


 Playwright locators are used to find elements on a web page before performing actions such as clicking, typing, selecting, or checking something. Playwright recommends user-facing locators such as getByRole(), getByText(), getByLabel(), getByPlaceholder(), and getByTestId() because they can make tests easier to understand and maintain.

If you are learning Playwright automation testing, understanding locators is one of the first skills you should master.

What Is a Playwright Locator?

Think of a locator like an address.

If you want to visit your friend's house, you need an address. In Playwright, you need a locator to tell the test which button, textbox, link, or other element it should use.

For example:

await page.getByRole('button', { name: 'Login' }).click();


Here, Playwright finds the Login button and clicks it.

Playwright locators are also designed to work with its auto-waiting and retry behavior. The official documentation recommends locators that describe elements in a way similar to how a user sees them.

Why Are Playwright Locators Important?

A test can fail if it cannot find the correct element.

For example, imagine a login page containing:

  • Username field

  • Password field

  • Login button

  • Forgot password link

Your automation script needs a reliable way to identify each element.

A good locator can make your test:

  • easier to read

  • easier to maintain

  • less dependent on page structure

  • more similar to real user behavior

  • less likely to break when the UI changes

This is one reason Playwright recommends user-facing locators instead of depending heavily on long CSS or XPath selectors.

Types of Playwright Locators

The most useful Playwright locators include:

  1. getByRole()

  2. getByText()

  3. getByLabel()

  4. getByPlaceholder()

  5. getByAltText()

  6. getByTitle()

  7. getByTestId()

  8. CSS selectors

  9. XPath selectors

Let's understand them with simple examples.

1. getByRole()

getByRole() finds an element using its accessible role.

Example:

await page.getByRole('button', { name: 'Login' }).click();


This tells Playwright:

Find a button named Login and click it.

You can use roles such as:

  • button

  • link

  • textbox

  • checkbox

  • heading

  • radio

  • combobox

  • list

  • listitem

Example:

await page.getByRole('link', { name: 'Contact Us' }).click();


This is usually easier to understand than a long CSS selector.

Why should you prefer getByRole()?

Because it describes the element from the user's point of view.

For example:

await page.getByRole('button', { name: 'Submit' }).click();


is easier to understand than:

await page.locator('#container > div:nth-child(3) > button').click();


The second selector depends heavily on the page structure and may break after a UI change.

The Playwright documentation specifically recommends prioritizing user-facing attributes and explicit testing contracts.

2. getByText()

Use getByText() when you want to find an element using visible text.

Example:

await page.getByText('Welcome to Playwright').click();


You can also use a regular expression:

await page.getByText(/Welcome to Playwright/i).click();


This can be useful when the exact text may have small differences.

3. getByLabel()

getByLabel() is useful for form fields that have labels.

For example, if your page contains:

<label>Email</label>

<input type="email">


You can write:

await page.getByLabel('Email').fill('test@example.com');


This makes the test easy to understand.

Instead of saying:

Find the second input box.

you are saying:

Find the field labelled Email.

That is much closer to how a person understands the page.

4. getByPlaceholder()

Some forms use placeholder text.

Example:

await page.getByPlaceholder('Enter your email').fill('test@example.com');


This can be useful when the placeholder is stable and meaningful.

However, do not add random placeholder-based selectors just because they are available. Choose the locator that represents the element most reliably.

5. getByAltText()

This locator is useful for images with meaningful alternative text.

Example:

await page.getByAltText('Playwright logo').click();


It can be useful when testing image links or accessible image elements.

6. getByTitle()

If an element has a title attribute, you can locate it with:

await page.getByTitle('Close').click();


This can be useful for buttons or icons that expose a stable title.

7. getByTestId()

Sometimes a development team adds a dedicated testing attribute.

Example:

<button data-testid="login-button">Login</button>


Then your test can use:

await page.getByTestId('login-button').click();


This can be a very useful approach when the development and testing teams agree on stable test IDs.

8. CSS Selectors

Playwright also supports CSS selectors.

Example:

await page.locator('#login-button').click();


Or:

await page.locator('.login-button').click();


CSS can be useful when there is a clear and stable selector.

But avoid extremely long selectors based on the page's DOM structure.

For example:

await page.locator('div:nth-child(2) > div:nth-child(3) > button').click();


This type of selector can become fragile when developers change the page layout.

9. XPath in Playwright

Playwright supports XPath selectors.

Example:

await page.locator('//button[text()="Login"]').click();


XPath can solve certain difficult element-location problems.

However, Playwright's documentation does not recommend relying on CSS or XPath when a more user-facing locator can be used.

Which Playwright Locator Should You Use?

A simple approach is:

Situation

Recommended locator

Button

getByRole()

Link

getByRole()

Heading

getByRole()

Form field with label

getByLabel()

Visible text

getByText()

Placeholder

getByPlaceholder()

Image

getByAltText()

Stable test attribute

getByTestId()

Special CSS requirement

locator()

Special XPath requirement

XPath

The goal is not to use the fanciest locator.

The goal is to use a locator that is clear, stable and meaningful.

Playwright Locator Example: Login Test

Here is a simple login test:

import { test, expect } from '@playwright/test';


test('User can login', async ({ page }) => {


  await page.goto('https://example.com/login');


  await page.getByLabel('Username').fill('testuser');


  await page.getByLabel('Password').fill('password123');


  await page.getByRole('button', { name: 'Login' }).click();


  await expect(

    page.getByText('Welcome')

  ).toBeVisible();


});


Notice how every action is easy to understand.

  1. Open the login page.

  2. Fill the username.

  3. Fill the password.

  4. Click Login.

  5. Check that Welcome appears.

This style makes automation easier for beginners to read.

Do Playwright Locators Automatically Wait?

Yes.

Playwright performs actionability checks before performing actions. For example, before clicking an element, Playwright checks whether the locator resolves correctly and whether the element is visible, stable, able to receive events and enabled.

That means you usually do not need to write unnecessary manual waits such as:

await page.waitForTimeout(5000);


A better approach is normally to use locators and Playwright's built-in waiting behavior.

For example:

await page.getByRole('button', { name: 'Login' }).click();


Playwright waits for the button to become actionable before clicking it.

Playwright Locator vs CSS Selector

The biggest difference is how you describe the element.

CSS often describes the HTML structure.

A role locator can describe the element's purpose.

For example:

await page.getByRole('button', { name: 'Login' }).click();


is easier to understand than:

await page.locator('form div:nth-child(3) button').click();


If the developer changes the layout but keeps the Login button accessible in the same way, the role-based locator may continue working.

Playwright Locator vs XPath

XPath is powerful, but it can become difficult to maintain when it depends heavily on the DOM structure.

For example:

//div[2]/div[3]/button


does not tell a future tester what the button actually does.

Compare that with:

page.getByRole('button', { name: 'Login' })


The second version explains itself.

That is an important quality difference in a real automation framework.

How to Choose a Good Locator

Use this simple rule:

Choose the locator that best describes how a real user would identify the element.

A practical preference order is:

  1. Role

  2. Label

  3. Text

  4. Placeholder

  5. Test ID

  6. CSS

  7. XPath

This is not a strict rule for every project. Your application's HTML, accessibility implementation and testing requirements should guide the final choice.

Common Playwright Locator Mistakes

Mistake 1: Using long CSS selectors

Avoid selectors that depend on many parent and child elements.

They can break when the UI changes.

Mistake 2: Using XPath for everything

XPath is not automatically the best locator just because it can find an element.

Use it when it genuinely solves a problem.

Mistake 3: Using nth() everywhere

For example:

await page.getByRole('button').nth(2).click();


This says:

Click the third button.

But what happens if another button is added later? 

A more specific locator is usually easier to maintain.

Mistake 4: Using fixed waits

Avoid using fixed delays as the main solution for synchronization problems.

Playwright already provides automatic waiting for many actions.

Mistake 5: Choosing unstable attributes

Do not build your entire test framework around dynamically generated class names or changing DOM structures.

How to Debug a Locator

If a locator is not working, Playwright provides tools that can make debugging easier.

You can run tests in UI Mode:

npx playwright test --ui


Playwright's UI Mode provides features such as a locator picker and allows you to inspect test execution visually.

You can also use Trace Viewer to inspect what happened during a test.

A trace can help you understand:

  • what action ran

  • what page was open

  • what the browser displayed

  • where the test failed

  • what happened before the failure

Playwright's Trace Viewer is designed specifically for exploring recorded test traces.

Playwright Locators Interview Questions

What is a locator in Playwright?

A locator is a way to identify an element on a web page so Playwright can interact with it.

Which locator is recommended in Playwright?

Playwright recommends user-facing locators such as getByRole(), getByText(), and getByLabel() where they fit the application.

Does Playwright support XPath?

Yes. Playwright supports XPath selectors, although user-facing locators are generally preferred when appropriate.

Does Playwright automatically wait for elements?

Yes. Playwright performs actionability checks before many actions and waits until the required conditions are met.

Is CSS better than XPath?

There is no universal winner. The best locator is the one that is stable, understandable and appropriate for the element.

Can I learn Playwright without knowing locators?

You can start without knowing them, but you cannot become effective at Playwright automation without understanding how locators work.

Frequently Asked Questions

What are Playwright locators?

Playwright locators are methods used to find elements on a web page so automated tests can interact with them.

What is getByRole in Playwright?

getByRole() finds an element based on its accessible role and, when specified, its accessible name.

What is getByText in Playwright?

getByText() finds an element using its visible text.

What is getByLabel in Playwright?

getByLabel() finds form controls associated with a label.

Which Is Better for Playwright: CSS or XPath? 

Use CSS or XPath when they are appropriate, but prefer resilient, user-facing locators when possible.

Why are my Playwright locators failing?

Common reasons include incorrect selectors, changed page content, duplicate elements, unstable attributes, frames, timing issues, or elements that are not yet actionable.

Final Answer

If you are learning Playwright, locators should be one of your first major topics.

Start with:

getByRole()

then learn:

getByText()

getByLabel()

getByPlaceholder()

getByTestId()

After that, learn CSS and XPath selectors for situations where they are actually useful.

The most important lesson is simple:

Do not choose a locator only because it works today. Choose one that is likely to remain understandable and stable when the application changes.

Learn Playwright Automation Testing

If you want structured Playwright training covering automation frameworks, API testing, cross-browser testing, Git, Jenkins, CI/CD, projects and interview preparation, explore the Playwright Masters training program.

Playwright Automation Testing Course

Playwright Syllabus

Playwright Course Fees

Contact Playwright Masters


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide