Playwright getByRole vs getByText vs CSS vs XPath: Complete Locators Comparison
A Playwright test becomes much easier to maintain when it can reliably find the right element.
Imagine a login page with a Username field, Password field, and Sign In button. A tester could find these elements in several ways:
page.getByRole('button', { name: 'Sign In' });
or:
page.getByText('Sign In');
or:
page.locator('#login-button');
or even:
page.locator('//button[@id="login-button"]');
All four approaches can potentially locate an element, but they do not communicate the same thing.
That is why understanding a Playwright locators comparison is important.
Playwright currently provides several built-in locator strategies. Its documentation recommends prioritizing user-facing locators and explicit testing contracts rather than selectors tightly connected to implementation details.
In this guide, we will compare getByRole(), getByText(), CSS, and XPath using simple examples.
If you are building your Playwright automation skills from the basics, the PlaywrightMasters learning resource provides a broader path covering Playwright automation testing concepts, tools, and practical topics.
What Is a Locator in Playwright?
A locator tells Playwright which element you want to work with.
For example:
await page.getByRole('button', { name: 'Login' }).click();
Here:
getByRole() is the locator method.
button is the element's role.
Login is its accessible name.
click() tells Playwright what to do.
Locators are important because Playwright uses them as part of its auto-waiting and retry behavior. The locator is resolved against the current page when an action or assertion needs the element.
A good locator should be:
Easy to understand
Specific enough to identify the correct element
Stable when the UI changes
Close to how a user interacts with the application
Easy for another tester to maintain
Quick Comparison
There is no universal selector that should be used for every situation.
The important question is:
What information gives this element a stable identity?
1. Playwright getByRole()
getByRole() identifies elements according to their accessibility role and accessible name.
Example:
await page.getByRole('button', { name: 'Sign In' }).click();
This tells us:
Find the button that users know as "Sign In".
Playwright supports roles such as:
button
link
heading
checkbox
textbox
radio
combobox
listitem
table
row
dialog
and many others.
Example
Suppose the HTML is:
<button>Sign In</button>
You can write:
await page.getByRole('button', { name: 'Sign In' }).click();
This is usually easier to understand than:
await page.locator('button.login-button').click();
The first version explains the element from a user's perspective.
When should you use getByRole()?
Use it when the element has a meaningful semantic role.
Examples:
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByRole('link', { name: 'Contact Us' }).click();
await page.getByRole('checkbox', { name: 'Remember me' }).check();
await page.getByRole('heading', { name: 'Dashboard' }).isVisible();
For interactive elements, Playwright specifically recommends role locators when appropriate.
2. Playwright getByText()
getByText() finds an element using its text content.
Example:
await expect(page.getByText('Order completed')).toBeVisible();
This is useful when the text itself is the important information.
For example:
<div>Payment successful</div>
You could write:
await expect(page.getByText('Payment successful')).toBeVisible();
You can also use an exact match:
page.getByText('Payment successful', { exact: true });
Or a regular expression:
page.getByText(/payment successful/i);
Playwright normalizes whitespace when matching text.
When should you use getByText()?
It works particularly well for:
Confirmation messages
Status messages
Product names
Headings
Informational content
Visible labels that are not better represented by another locator
For example:
await expect(page.getByText('Profile updated successfully')).toBeVisible();
However, for an interactive button, this is often clearer:
page.getByRole('button', { name: 'Save' })
instead of:
page.getByText('Save')
The reason is that the role tells the test what type of element it expects.
3. CSS Selectors in Playwright
CSS selectors identify elements using HTML structure, classes, IDs, attributes, and other CSS selector features.
Example:
await page.locator('#username').fill('rakesh');
Another example:
await page.locator('input[name="email"]').fill('user@example.com');
CSS selectors are a normal and powerful way to identify DOM elements. CSS supports selectors based on element types, IDs, classes, attributes, relationships, and more.
When is CSS useful?
CSS can be useful when your application provides stable technical attributes.
For example:
<input data-testid="email-input">
You could use:
await page.locator('[data-testid="email-input"]').fill('user@example.com');
However, if the application has a dedicated test ID, Playwright's getByTestId() can make the intent clearer:
await page.getByTestId('email-input').fill('user@example.com');
CSS is also useful when dealing with a component where the DOM contract is intentionally stable.
4. XPath in Playwright
XPath is a path-based language used to identify nodes in an HTML or XML document.
In Playwright:
await page.locator('//button[@id="login"]').click();
You can also make the syntax explicit:
await page.locator('xpath=//button[@id="login"]').click();
Playwright supports XPath, but its documentation warns that selectors strongly tied to DOM structure can become fragile when the implementation changes. XPath also does not pierce shadow roots.
Example
Consider:
<div class="login-container">
<button id="login">Sign In</button>
</div>
An XPath could be:
page.locator('//div[@class="login-container"]/button');
But a shorter and more stable locator may be:
page.getByRole('button', { name: 'Sign In' });
The second locator does not care whether the button is inside one <div> or three nested <div> elements.
getByRole vs getByText vs CSS vs XPath
Here is a practical comparison.
The table is not saying that one method always wins.
The right choice depends on the element and the application's structure.
Real Example: Shopping Cart
Suppose your page contains:
<article>
<h2>Playwright Course</h2>
<button>Add to Cart</button>
</article>
You could locate the product using:
page.getByText('Playwright Course');
Then locate its button:
page
.getByRole('article')
.filter({ hasText: 'Playwright Course' })
.getByRole('button', { name: 'Add to Cart' })
.click();
This style is powerful because the locator first identifies the correct product and then finds the button inside it.
Playwright supports chaining and filtering locators to narrow down the search.
Which Locator Should a Beginner Learn First?
A beginner should understand the following order of thinking:
Step 1: Can I identify it by role?
Try:
getByRole()
Step 2: Can I identify meaningful visible text?
Try:
getByText()
Step 3: Is there a stable test contract?
Consider:
getByTestId()
Step 4: Is there a stable CSS attribute?
Use:
locator('...')
Step 5: Do I genuinely need XPath?
Use:
locator('xpath=...')
This is not a rigid law. It is a useful starting strategy.
Common Locator Mistakes
Mistake 1: Using long XPath
Avoid:
page.locator('/html/body/div[2]/div[1]/div[3]/button');
A small layout change can break it.
Mistake 2: Depending on generated CSS classes
Avoid selectors such as:
page.locator('.css-8x72ab-button');
If the class is generated by a framework, it may change.
Mistake 3: Using text when role is clearer
Instead of:
page.getByText('Login').click();
consider:
page.getByRole('button', { name: 'Login' }).click();
when Login is actually a button.
Mistake 4: Choosing a selector that matches many elements
For example:
page.locator('button').click();
may match multiple buttons and create a strictness problem.
Make the locator more specific.
Best Practices for Reliable Playwright Locators
Prefer meaningful user-facing locators.
Use getByRole() for semantic interactive elements.
Use getByText() when visible text is the useful identity.
Use test IDs when your team has intentionally created a testing contract.
Use CSS when stable attributes make it the clearest option.
Use XPath when its navigation capability solves a real problem.
Avoid selectors based on fragile DOM positions.
Keep locators readable.
Narrow large result sets with filtering.
Keep locator decisions consistent across your project.
If you are building your Playwright foundation, a dedicated Playwright Locators learning resource can be used alongside the official documentation.
For a broader learning path, the Playwright Roadmap can help organize topics from beginner concepts toward practical automation projects.
A Simple Decision Guide
Ask these questions:
Is it a button, link, checkbox, heading, or another semantic element?
Use:
getByRole()
Is the visible text itself what identifies the element?
Use:
getByText()
Does your application provide a stable test ID?
Use:
getByTestId()
Do you have a stable CSS attribute?
Use:
locator('...')
Do you need a complex relationship or legacy DOM navigation?
Consider:
locator('xpath=...')
The goal is not to avoid CSS and XPath completely. The goal is to choose selectors that remain understandable and useful when the application changes.
Frequently Asked Questions
Is getByRole better than XPath in Playwright?
For many user-facing interactive elements, getByRole() communicates intent more clearly and is recommended by Playwright's locator guidance. XPath can still be useful for cases where XPath's navigation capabilities are genuinely needed.
Is getByText good for buttons?
It can locate button text, but when the element is a button, getByRole('button', { name: '...' }) generally communicates the intended element more clearly.
Is CSS faster than getByRole?
Locator choice should not be based only on a simplistic "which selector is fastest" assumption. Reliability, clarity, and maintainability are usually more important when designing end-to-end tests.
Should I stop using XPath?
No. XPath remains supported by Playwright. The important point is to avoid unnecessarily fragile XPath expressions that depend heavily on changing DOM structure.
What is the easiest Playwright locator for beginners?
getByRole() and getByText() are good starting points because they describe elements in terms that are easier to understand.
Can Playwright combine locators?
Yes. Locators can be chained and filtered to narrow down a specific element.
What is the most maintainable locator?
A locator based on a stable, meaningful identity is generally easier to maintain than one based on fragile DOM position. In many applications, that means a role plus accessible name, text, or an intentional test ID.
Can CSS and XPath be used together with Playwright?
Yes. Playwright supports both through page.locator(), including explicit css= and xpath= prefixes.
Conclusion
There is no single locator syntax that solves every automation problem.
For most everyday UI interactions, start by asking how the user or application meaningfully identifies the element. getByRole() is particularly useful for semantic interactive elements, while getByText() works well when visible text is the important identity.
CSS and XPath remain valuable tools when you need lower-level DOM selection.
The strongest Playwright tests are not the ones with the cleverest selectors. They are the ones where another tester can immediately understand why the locator identifies that element.

Comments
Post a Comment