In Playwright Java, element locators are used to identify and interact with elements on a web page. They act as pointers that help your test scripts find buttons, links, or text fields during automation. Among the various locator strategies, the Playwright Java Selector by Text is one of the most intuitive and human-readable methods for targeting elements.
This selector allows you to locate elements based on their visible text content, making your test scripts easier to understand and maintain. Instead of relying on complex CSS selectors or fragile XPath expressions, you can match the text users actually see on the screen.
Using text-based locators is especially useful when dealing with dynamic or content-driven applications, where attributes like IDs or classes may change frequently. By selecting elements directly through their displayed text, you ensure that your tests remain stable and closely aligned with real user behavior.
What is Playwright Java Selector by Text?
The Playwright Java Selector by Text is a powerful locator strategy that helps you find elements on a web page using their visible text content. Instead of targeting elements by technical attributes like IDs, classes, or XPath, this method identifies elements exactly as users see them through the text displayed on the screen.
In Playwright, this approach is commonly implemented using methods such as getByText(). For example, if you want to click a button labeled “Login,” you can simply use:
page.getByText("Login").click();
This command tells Playwright to find the element that contains the visible text “Login” and perform an action on it.
You might also see this method described as Playwright Java get element by text or Playwright Java find element by text content. These terms all refer to the same concept of locating elements based on text rather than HTML structure.
Using Selector by Text is particularly useful when working with dynamic front-end applications where element attributes like IDs or classes frequently change. In such cases, text-based locators remain consistent because visible text usually stays the same. Compared to CSS or XPath locators, which can be more fragile and harder to read, text selectors make your test scripts more maintainable, readable, and user-oriented.
Syntax and Basic Example
The getByText() method in Playwright Java allows you to locate elements by their visible text. This makes it one of the simplest and most readable ways to interact with web elements. You can even test it using a local HTML file before applying it to a real project.
Below is a complete Playwright Java by text selector example using a local HTML file.
You can download the sample Locators.html file and place it inside the D drive.

Java Example to Locate Element by Text
Now, create a Java class file named GetByTextExample.java and paste the following code:
package com.example.test;
import com.microsoft.playwright.*;
public class GetByTextExample {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
// Launch browser
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
// Create a new context and page
BrowserContext context = browser.newContext();
Page page = context.newPage();
// Listen for JavaScript alert dialog
page.onDialog(dialog -> {
System.out.println("Alert Message: " + dialog.message());
dialog.accept(); // Click OK to close the alert
});
// Load local HTML file (update path as per your setup)
page.navigate("file:///D:/Locators.html");
// Locate and click the "Submit" button by visible text
page.getByText("Submit").click();
System.out.println("Clicked on the Submit button successfully.");
// Close the browser
browser.close();
}
}
}
How It Works
- Playwright opens your local HTML file using the file:// protocol.
- It looks for any element displaying the text “Submit” on the page.
- Once found, it performs the .click() action on that element.
This approach differs from CSS or XPath locators because it matches visible text content, not attributes or structure. As a result, it is more human-readable, reliable, and easier to maintain, especially for content-heavy or frequently changing web pages.
Exact Text Match vs Partial Text Match
When working with the Playwright Java Selector by Text, you can locate elements using either an exact text match or a partial text match, depending on how specific you want your locator to be.
An exact text match means Playwright looks for elements whose visible text exactly matches the string you provide. For example, if your local HTML file has a button with the text “Submit”, you can click it using:
page.getByText("Submit").click();
This tells Playwright to interact only with elements that have text content that matches “Submit” exactly, with no extra spaces or characters. This approach is best when the text content is stable and you want precise targeting. It is often referred to as a Playwright Java exact text match.
On the other hand, a partial text match allows you to locate elements even if you specify only part of their visible text. This is helpful when you are unsure of the full text or when the text may slightly vary. For example:
page.getByText("Sub").click();
In this case, Playwright will find and interact with any element containing “Sub” within its text, such as “Submit” or “Subscribe”. This method is known as a Playwright Java partial text match and offers more flexibility, especially for dynamic or localized content.
In summary, an exact text match ensures accuracy, while a partial text match provides flexibility. You can choose either based on your test scenario and the consistency of text values in your application.
Advanced Usage with Text Matching Strategies
Playwright provides several powerful text-matching strategies that make it easier to locate elements even when the text on the page varies slightly. These strategies help you handle situations such as case sensitivity, extra whitespace, or text patterns.
By default, Playwright performs a case-sensitive exact match when using getByText(). However, if your application displays text in different cases (for example, “Login” vs “login”), you can make your locator more flexible by using regular expressions (regex).
Here’s an example demonstrating how to use regex for text matching in Playwright Java:
page.getByText(Pattern.compile("login", Pattern.CASE_INSENSITIVE)).click();
In this example, Playwright will find and click the button whether it displays “Login”, “LOGIN”, or “login”. This makes your locator more robust against small text variations.
Whitespace differences can also cause locators to fail. To handle such cases, you can use regex patterns that ignore extra spaces. For example:
page.getByText(Pattern.compile("\\s*Login\\s*")).click();
This pattern ensures that even if the text includes leading or trailing spaces, Playwright still recognizes it.
These Playwright Java text matching strategies make your selectors more adaptable to real-world UI scenarios. By combining regex or partial matching, you can ensure that your tests remain stable and accurate even when the application’s visible text changes slightly due to formatting, styling, or localization.
Using hasText for Nested Element Selection
In Playwright Java, both getByText()
and hasText
can be used to locate elements by visible text, but they serve slightly different purposes. The getByText()
method is used when you want to find an element that directly contains specific text. In contrast, the Playwright Java hasText option is useful when the text you want to match is nested inside another element.

For example, imagine your HTML structure looks like this:
<div class="user-card">
<span>Profile</span>
</div>
If you use getByText("Profile")
, it will locate the inner <span>
element. But if you want to interact with the parent <div>
that contains this text, you can use hasText
inside the locator options.
Here’s how it works in Playwright Java:
page.locator("div", new Locator.LocatorOptions().setHasText("Profile")).click();
In this example, Playwright finds the <div>
element whose nested content includes the text “Profile”, and then performs a click action on it.
You should use getByText() when you need to target elements directly by visible text, such as buttons or links. Use hasText when you need to locate parent or container elements that include specific text inside them. This makes Playwright Java hasText especially powerful for complex page structures or when testing UI components with nested text elements.
Handling Dynamic Content or Multiple Matches
When working with real-world web applications, you may encounter situations where multiple elements share the same visible text. For example, there could be several “Edit” or “Delete” buttons on a page. In such cases, Playwright provides flexible strategies to accurately target the right element, even when text content overlaps.
One common approach is to use the nth locator, which allows you to interact with a specific occurrence of an element. For example:
// Click the second "Edit" button on the page
page.getByText("Edit").nth(1).click();
Here, Playwright will locate all elements containing the text “Edit” and then click on the second one (since index counting starts from 0).
Another strategy is to use filtering options to refine your selection based on element hierarchy or attributes. For instance, you can narrow down your locator to a particular section of the page:
// Locate an element with text "Edit" inside a specific container
page.locator("div.user-card").getByText("Edit").click();
This ensures that Playwright interacts only with the “Edit” button inside the .user-card
container, not others elsewhere on the page.
In scenarios where the text is dynamic or may change slightly, you can also use a Playwright Java text content locator combined with flexible matching techniques like regex or partial text. This helps ensure that your tests remain stable even when the application UI evolves.
By using these techniques, you can precisely handle dynamic content, prevent false matches, and make your Playwright Java tests more reliable across multiple elements sharing similar text.
Complete Example: Playwright Java by Text Selector
Here’s a complete example showing how to use Playwright Java by text selector in a real-world scenario. We’ll use the same local HTML file (e.g., file:///D:/Locators.html) that contains a Submit button displaying an alert when clicked.
This test combines getByText() for direct text matching and hasText() for nested element selection.
package com.example.test;
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class PlaywrightByTextExample {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext context = browser.newContext();
Page page = context.newPage();
// Load the local HTML file
page.navigate(Paths.get("D:\\Locators.html").toUri().toString());
// Handle alert before clicking
page.onceDialog(dialog -> {
System.out.println("Alert Message: " + dialog.message());
dialog.accept();
});
// Example 1: Click button by exact text
page.getByText("Submit").click();
// Example 2: Click nested element using hasText
page.locator("button", new Page.LocatorOptions().setHasText("Submit")).click();
System.out.println("Test completed successfully.");
browser.close();
}
}
}
Explanation:
- page.getByText(“Submit”).click(): Finds the element with exact text “Submit” and clicks it.
- page.onceDialog(…) — Handles the alert popup triggered by the click event.
- page.locator(“button”, new Page.LocatorOptions().setHasText(“Submit”)): Uses the Playwright Java hasText option to find a <button> that contains the text “Profile”, even if it’s nested.

This example demonstrates how to efficiently combine getByText() and hasText() when automating local HTML files with Playwright Java by text selector.
Conclusion
The Playwright Java Selector by Text makes it easy to create clear and maintainable automation scripts. Instead of relying on complex CSS or XPath expressions, you can directly locate elements using visible text, just as a real user would.
This approach simplifies your test code and improves readability, especially in projects where UI elements change frequently. By using text-based locators, your tests remain stable even when attributes like IDs or classes are updated.
In real-world automation, adopting the Playwright Java Selector by Text strategy helps you write tests that are not only more reliable but also easier to understand, debug, and maintain over time.