Last updated on August 2nd, 2026 at 08:55 am
When writing automated tests, finding and interacting with page elements is crucial. This is where Playwright locators come into play. Locators are used to target elements on the page, such as buttons, links, input fields, and more. In this tutorial, you’ll learn how to use Playwright locators, see real-world examples, and understand the different types available.
Whether you’re new to automation or switching from Selenium to Playwright, this guide will help you understand everything you need to know about using locators effectively.
This locator guide is part of a larger Playwright tutorial for beginners that covers everything from setup to real-world examples.
As your Playwright tests grow, managing locators efficiently becomes just as important as choosing the right locator. See How to Use Playwright Object Repository in Framework to learn how centralized locators improve stability and maintenance.
This guide is verified against Playwright 1.62. Locator behavior has been stable across recent releases, but if you’re on an older version and something here doesn’t match what you see, check the Playwright release notes for changes.
What Are Locators in Playwright?
A locator in Playwright is an object that represents a way to find one or more elements on a page at any given moment. Locators are Playwright’s high-level API for finding and interacting with page elements, and they auto-wait and retry on failure instead of failing the instant an element isn’t ready. That auto-waiting is what separates them from older, static selector methods like querySelector.
They are used with the page.locator() method or built-in helper locators like getByText, getByRole, and others.
Why Locators Matter for Test Automation
Here are a few reasons why Playwright locators are preferred:
- Auto-wait for elements to be visible and stable.
- Built-in retries for flaky tests.
- Cleaner syntax than raw selectors.
- Easy debugging and improved test reliability.
They help you build stable test automation that works across browsers.
If you’re learning locators for real-world automation, it’s also useful to understand how Playwright compares with traditional tools. A comparison like Playwright vs Selenium helps clarify why modern teams prefer Playwright for stable and reliable test automation.
Types of Locators in Playwright
Playwright offers a wide range of locator strategies. Here’s a complete list, with the most commonly searched ones covered in detail below.
1. CSS Selectors
CSS selectors in Playwright let you target elements using tags, classes, IDs, attributes, and combinations of these. They’re widely used and easy to understand, especially for beginners.
page.locator('button.submit')Read the full guide on CSS selectors in Playwright →
2. Locate Elements by Class
One of the most common ways to use a CSS selector is to target an element directly by its class attribute. This is useful when an element doesn’t have a unique ID but has a distinct class name.
// Locate a single class
page.locator('.user-input')
// Locate an element with multiple classes
page.locator('.user-input.special-field')
// Locate a specific tag with a class
page.locator('input.user-input')Keep in mind that class names are more likely to change during UI refactors than a data-testid, so treat class-based locators as a fallback rather than your first choice for critical flows.
3. Locate Elements by ID
IDs are meant to be unique within a page, which makes them one of the most reliable ways to target an element with a CSS selector.
// Locate by ID
page.locator('#username-input')
// Combine ID with an attribute for extra precision
page.locator('#username-input[type="text"]')If your application already assigns stable, meaningful IDs to form fields and interactive elements, ID-based locators are fast and easy to read. If IDs are auto-generated or change between builds, prefer getByTestId() instead (covered below).
4. Text Locator
Text locators make it easy to find elements based on the visible text on the page. This is especially helpful when working with buttons, links, or labels that users interact with, instead of relying on IDs or classes.
page.getByText('Submit')Read the full guide on text locators in Playwright →
5. Role Locator
Role locators select elements based on their ARIA role, such as button, link, textbox, or checkbox. This makes tests more readable and accessible, and aligns them with how real users and assistive technology interact with the page.
page.getByRole('button', { name: 'Submit' })See how getByRole() works in Playwright, with real examples →
6. Placeholder Locator
Placeholder locators select input fields based on their placeholder text, which is useful when forms don’t have labels or unique IDs.
page.getByPlaceholder('Enter your email')Learn how to use getByPlaceholder() in Playwright →
7. Label Locator
Label locators select form elements based on their associated <label> text, which is helpful for input boxes, checkboxes, and radio buttons.
page.getByLabel('Email Address')Check out the detailed guide on getByLabel() in Playwright →
8. Title Locator
Title locators select elements based on their title attribute, which is useful for icons, buttons, or links that only expose their purpose through a tooltip.
page.getByTitle('Close')Discover how to use getByTitle() in Playwright →
9. Alt Text Locator
Alt text locators find image elements based on their alt attribute, which is ideal for sites that use descriptive alternative text for images.
page.getByAltText('Logo')Learn how to use getByAltText() in Playwright step-by-step →
10. Test ID Locator
Test ID locators target elements using custom data-testid attributes, commonly added by developers specifically for testing. Because they don’t change with styling or copy updates, they’re one of the most stable locator strategies available.
page.getByTestId('signup-button')Find out how to use getByTestId() in Playwright →
11. XPath Locator
XPath locators let you select elements using XML path expressions. They’re powerful for complex or deeply nested HTML structures, and can navigate both forward and backward in the DOM.
page.locator('//input[@id="username"]');Find out how to use XPath in Playwright →
Best Locator Strategy for Stable Tests
- Use
getByRolefor accessibility-based selection. - Use
getByTestIdfor stable automation. - Use ID or class selectors when the app already provides stable ones.
- Avoid XPath unless necessary.
In my experience testing production apps, teams that lean heavily on CSS class locators end up rewriting large chunks of their suite after every UI redesign. I’d rather spend five minutes asking a developer to add a data-testid than debug fifty broken selectors after a rebrand.
One mistake I still see even experienced testers make: reaching for XPath by default because it feels familiar from Selenium. Playwright’s getBy* methods cover almost every case an XPath expression would, with far less fragility.
Which Locator Should You Use?
| Situation | Recommended Locator |
|---|---|
| App has custom test attributes | getByTestId() |
| Testing accessibility-focused UI | getByRole() |
| Element has stable, visible text | getByText() |
| Form field with a label | getByLabel() |
| App already has stable IDs | locator('#id') |
| No other stable attribute exists | locator() with CSS or XPath, as a last resort |
Preparing for interviews? Check Playwright interview questions and answers.
Playwright Locators Examples
Before jumping into locator syntax, it helps to see exactly how a real element’s attributes map to each locator type. Here’s how to find them, followed by a live example.
How to Find Locators Using Browser DevTools
Before you can write a locator, you need to know what’s actually available on the element. Right-click the element in your browser and select Inspect to open DevTools. In the Elements panel, look at the highlighted HTML: check for an id, class, data-testid, role, or visible text, since any of these can become a locator.
As a rule, prefer whichever attribute is least likely to change: a data-testid or ARIA role is usually safer long-term than a class name tied to current styling.

Let’s say you have an element with the following HTML structure:
<form>
<!-- Label Locator -->
<label for="username-input">Username</label>
<!-- Input element with all necessary attributes -->
<input
id="username-input" <!-- ID Locator -->
name="username"
type="text"
role="textbox" <!-- Role Locator -->
placeholder="Enter your username" <!-- Placeholder Locator -->
title="Username Field" <!-- Title Locator -->
data-testid="usernameField" <!-- Test ID Locator -->
value="sampleuser" <!-- Text Locator -->
class="user-input special-field" <!-- Class Locator -->
/>
</form>This element can be targeted in multiple ways using different Playwright locator strategies:
- CSS Selector:
page.locator('.user-input')orpage.locator('#username-input') - Class Locator:
page.locator('.special-field') - ID Locator:
page.locator('#username-input') - Role Locator:
page.getByRole('textbox', { name: 'Username' }) - Placeholder Locator:
page.getByPlaceholder('Enter your username') - Label Locator:
page.getByLabel('Username') - Title Locator:
page.getByTitle('Username Field') - Test ID Locator:
page.getByTestId('usernameField') - XPath:
page.locator('//input[@id="username-input"]')
Locator vs getBy in Playwright
Let’s compare the traditional locator() and modern getBy* methods
| Feature | locator() | getBy*() Methods |
|---|---|---|
| Flexibility | High (supports any selector) | Medium (semantic, focused) |
| Readability | Less readable | More readable |
| Accessibility | Needs manual role awareness | ARIA roles are built-in |
| Auto-wait | Yes | Yes |
In most cases, getByRole and getByText are preferred for clarity and long-term stability, especially in accessibility-focused apps.
Best Practices for Using Locators
- Prefer getByRole or getByText for stable and readable tests.
- Avoid using overly complex CSS selectors.
- Use getByTestId only when semantic selectors aren’t enough.
- Add custom
data-testidattributes in your app for testability. - Use locator().first(), locator().nth(), and locator().last() when dealing with multiple matches.
- Keep locator naming consistent across your test suite to reduce long-term maintenance effort.
What’s Next
Now that you know how to use Playwright locators to find and interact with elements, the next step is mastering more advanced locator strategies. XPath is a powerful way to target elements when simple locators are not enough. To deepen your locator skills with real examples, check out Locator XPath in Playwright, where we show how and when to use XPath effectively.
Understanding how to use locators effectively is one of the most important skills in automation testing. In real-world projects, testers spend a significant amount of time working with locators to identify elements reliably across browsers.
Strong locator strategies are often what separate beginner testers from experienced automation engineers. That’s exactly why interviewers dig into locator concepts so closely.
Final Words
Playwright locators are the backbone of any reliable test script. By using the right type of locator, whether it’s a class, ID, text match, ARIA role, or CSS selector, you can create readable, maintainable tests. For beginners, starting with getByRole, getByText, and getByLabel will make your journey smoother.
Frequently Asked Questions (FAQs)
What are locators in Playwright?
Locators in Playwright are used to find and interact with elements on a web page. They act as a reference to UI elements in your automated tests.
How many types of locators are there in Playwright?
Playwright supports multiple types of locators such as CSS selectors, class and ID selectors, getByRole, getByText, getByLabel, getByPlaceholder, getByAltText, getByTitle, and test ID locators.
How do I locate an element by class in Playwright?
Use a CSS selector with a dot prefix, for example page.locator(‘.user-input’). You can combine multiple classes with page.locator(‘.user-input.special-field’).
How do I locate an element by ID in Playwright?
Use a CSS selector with a hash prefix, for example page.locator(‘#username-input’). IDs are usually unique on a page, making this one of the most reliable locator strategies when the app assigns stable IDs.
What is the difference between locator and getBy in Playwright?
The locator() method is a generic way to select elements using CSS or XPath. The getBy* methods are more readable, semantic-based locators introduced for better accessibility and test reliability.
Can I combine multiple locators in Playwright?
Yes, you can chain locators in Playwright using methods like locator().first(), locator().nth(index), and locator().filter() to fine-tune element targeting.
One thought on “Playwright Locators: Complete Guide to 11 Types & Examples”
Great breakdown, Aravind! Emphasizing getByRole and getByLabel over raw CSS or XPath is definitely the right approach for writing maintainable Playwright suites. In our workflow, we pair clean Playwright locator strategies with Testomat.io for test reporting and management, which makes tracking regression results and feature coverage across builds effortless. Thanks for sharing!