How to Locate Elements in Playwright Java

If you’re diving into Playwright for Java automation and wondering “How do I locate elements accurately?”, you’re in the right place.

Locating elements is the foundation of any UI automation. If you get this wrong, your scripts will be flaky, hard to maintain, and bound to break. In this guide, we’ll explore all the different locator strategies in Playwright Java, along with examples.

Table of Contents

A locator is an object that identifies a specific web element on the page, such as:

  • A button
  • An input field
  • A heading
  • A table row

In Playwright Java, we use the Locator class to find elements. Once located, we can interact with them using methods like .click(), .fill(), .getTextContent(), etc.

Locator button = page.locator("button#submit");

Here, page.locator() is used to find the button with the id=”submit”. Once found, you can click, type into, or validate this element.

Think of locators as “element finders” that allow you to interact with parts of your UI.

Playwright’s locator engine is smarter than traditional Selenium-based frameworks. It automatically waits for the element to be:

  • Attached to the DOM
  • Visible on the screen
  • Enabled (not disabled)

This is called auto-waiting and reduces the need for manually adding Thread.sleep() or waits.

Example:

Locator inputBox = page.locator("#firstName]");
inputBox.fill("Playwright Java");

No need to wait! Playwright will handle it.

Let’s go through every kind of locator, one by one, with use cases and examples.

Please note that we will use our Playground website – https://testkru.com/Elements/TextFields throughout our examples, such that you can also try the examples on your own.

Text locators match visible text content of elements.

Locator signInLink = page.locator("text=Sign In");
  • It matches exactly Sign In
  • Case-sensitive by default
  • You can use regex for more complex matching.

Code Example –

In this example, we’ll use the Text Locator strategy to identify the highlighted element shown in the image below.

last name label field

The label text for this element is “2) Last Name With Placeholder”, so we’ll use that to locate it.

Locator labelLocator = page.locator("text=2) Last Name With Placeholder");

To verify whether the element was successfully located, we can use the innerText() method to retrieve its text. Don’t worry if you’re not familiar with the innerText() method yet, it simply returns the text of an element.

labelLocator.innerText()

Full code

import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/TextFields");

        // locating element
        Locator labelLocator = page.locator("text=2) Last Name With Placeholder");
        System.out.println(labelLocator.innerText()); // printing the text

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

2) Last Name With Placeholder

As, we were able to retrieve the text from the element, it confirms that the element was successfully located.

We can also use regular expressions (regex) with the Text Locator strategy to match elements based on flexible text patterns.

Playwright allows you to locate elements using regular expressions in text selectors.

Instead of using a strict match like “text=2) Last Name With Placeholder”, we can use:

Locator labelLocator = page.locator("text=/.*Last Name.*/");

Or with case-insensitive flag:

Locator labelLocator = page.locator("text=/.*last name.*/i");

Both of the above locators will help in locating the same label.

Common Regex Patterns

PatternMeaning
/^Start/Text starts with “Start”
/End$/Text ends with “End”
/Welcome/iCase-insensitive match for “Welcome”
/.*Log.*/Text contains “Log”
/[A-Za-z]+/Matches any word

We can also use Playwright’s getByText() method to locate and retrieve an element based on its visible text.

Syntax

Locator locator = page.getByText("text");

So, we can find the below highlighted element using page.getByText(“2) Last Name With Placeholder”).

last name label field
import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/TextFields");

        // locating element
        Locator labelLocator = page.getByText("2) Last Name With Placeholder");
        System.out.println(labelLocator.innerText()); // printing the text

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

2) Last Name With Placeholder

Note: getByText() also supports matching text using regular expressions, allowing you to locate elements with dynamic or partial text patterns.

In Playwright Java, CSS selectors are the primary and most powerful mechanism for identifying elements on a web page. They’re used with locator() to precisely and reliably interact with UI elements.

CSS Selectors work:

  • Across all modern web applications
  • With dynamic or deeply nested DOMs
  • For almost every element type

Syntax:

Locator element = page.locator("css-selector");

Examples:

// ID
page.locator("#username");

// Class
page.locator(".btn-primary");

// Descendant
page.locator("div.card > span.title");

// Multiple attributes
page.locator("input[type='email'][name='userEmail']");

Our focus will be on locating the element using a CSS selector and not on how to write one. Crafting effective CSS selectors is a topic that deserves its own dedicated post.

Code example

Let’s try to locate the highlighment element using the CSS locator strategy. This element is present on this page – https://testkru.com/Elements/TextMessages.

Plain text

Now, there are multiple ways to write the css locator for this element –

// using only id
page.locator("#plainText");

// including p tag as well
page.locator("p[id='plainText']");

We can use any of them, to locate the element. We will agin use innerText() method to show that we have successfully located the element.

import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/TextMessages");

        // locating element
        Locator textLocator = page.locator("p[id='plainText']");
        System.out.println(textLocator.innerText()); // printing the text

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

A Plain Text

We can use either of these options to locate the element. Once again, we’ll use the innerText() method to confirm that the element was successfully located.

XPath locators need no introduction, they’re among the most widely used strategies for finding elements, even in Selenium. We’ve covered XPath in detail, including tips on how to write efficient and reliable expressions, in a separate post.

XPath is a query language for selecting nodes in an XML/HTML document.

Examples

page.locator("//p[@id='plainText']");

// Button with exact text
page.locator("//button[text()='Submit']");

// Contains text
page.locator("//*[contains(text(),'Welcome')]");

// Relative path
page.locator("//div[@id='container']//a");

Code Example

Let’s try to locate the highlighment element using the Xpath locator strategy. This element is present on this page – https://testkru.com/Elements/TextMessages.

Plain text

The xpath of the highlighted element would be “//p[@id=’plainText’]”. Let’s use it to locate the element.

import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/TextMessages");

        // locating element
        Locator textLocator = page.locator("//p[@id='plainText']");
        System.out.println(textLocator.innerText()); // printing the text

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

A Plain Text

You can locate using simple tags too.

page.locator("button"); // using tag
page.locator("#login"); // using id
page.locator(".alert-danger"); // using class

This is similar to CSS selectors, just simplified.

ARIA stands for Accessible Rich Internet Applications.

An ARIA role is an attribute you can assign to an HTML element to describe its purpose or function on the page.

Think of it as the “job title” of the element.

For example:

  • A <button> element has the ARIA role of button
  • A <a> tag with an href has the role of link
  • A <input type="checkbox"> gets the role of checkbox

These roles don’t always need to be explicitly written, many are inferred automatically from the element type. But developers can also manually assign them using the role attribute:

<div role="button">Click Me</div>

Here, we’ve told the browser: “Even though this is a <div>, treat it like a button.”

Web developers use ARIA roles to describe what an element does, especially for screen readers or assistive technologies.

While these roles were originally introduced to help assistive technologies (like screen readers), they also give structure and meaning to the UI.

Let’s say someone is visually impaired and using a screen reader. When you tab through the page, the reader might say:

“Button: Submit”

That’s because it looks at the role of the element (button) and its name (visible label: Submit).

So even though ARIA roles were made for accessibility, they serve a larger purpose: helping us describe what each element does, rather than how it looks.

Playwright uses getByRole() to find elements based on their ARIA roles.

Instead of looking only at HTML tags or CSS, Playwright builds an accessibility tree (just like screen readers do). It then searches for the element that matches:

  • The role you provide (e.g., button, link)
  • And the element’s accessible name (text, aria-label, title, etc.)

This makes element selection more stable and closer to how users experience the page.

page.getByRole(AriaRole.<ROLE>, new Page.GetByRoleOptions().setName("Visible Text"));

So, if we want to locate a button with the text “Sign In”, we can do it like this:

page.getByRole(AriaRole.Button, new Page.GetByRoleOptions().setName("Sign In"));

Let’s try to locate the highlighted button on our playground website: https://testkru.com/Elements/Buttons.

Left click button

So, we can use the following code to locate the highlighted button using its ARIA role and accessible name:

page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Left click on me")).click();

We’ll also retrieve the text written on the button to show that the button was successfully located.

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

public class CodekruTest {

    public static void main(String[] args){
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/Buttons");

        // locating element
        Locator buttonLocator = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Left click on me"));
        System.out.println(buttonLocator.textContent());

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

Left click on me

Chained locators are used when you want to find an element within the context of another element. Instead of writing one long selector, you can locate a parent first, then search inside it for the child. This makes your code cleaner, more readable, and easier to maintain.

Syntax

Locator parent = page.locator("<parent>");
Locator child = parent.locator("<child>");

Or chain it directly:

Locator child = page.locator("<parent>").locator("<child>");

Let’s take the below element present on the page – https://testkru.com/Elements/TextFields.

first name with placeholder

As we can see, there’s a top-level ID called “textFieldElements” and a nested element with the ID "firstNamePlaceholder". So, we can use chained or nested locator strategy to target the desired element more precisely.

page.locator("#textFieldElements").locator("#firstNamePlaceholder");

Here’s the full code:

import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/TextFields");

        // locating element
        Locator labelLocator = page.locator("#textFieldElements").locator("#firstNamePlaceholder");
        System.out.println(labelLocator.innerText()); // printing the text

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

1) First Name Without Placeholder

When multiple elements match the same selector, and you want to interact with a specific one based on its position, Playwright provides the .nth(index) method.

When to Use

  • Multiple elements match the same locator
  • You want to interact with the first, second, or nth element
  • No unique identifier or text is available
Locator item = page.locator("<selector>").nth(index);

Note: Index is zero-based (i.e., .nth(0) targets the first match)

Let’s take the example of the buttons present on the page: https://testkru.com/Elements/Buttons.

buttons

As shown in the image above, the XPath //div[@id='content']//button matches 7 buttons. If we want to target the third button specifically, we can use the nth index strategy as shown below.

Locator thirdButton = page.locator("//div[@id='content']//button").nth(2);

We’re using nth(2) to select the third element because indexing is 0-based, which means the first element has an index of 0.

Whole code:

import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {
        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium(). // Creating a "Browser" instance
                launch(new BrowserType.LaunchOptions().setHeadless(false));  // visually opening the browser

        Page page = browser.newContext().newPage(); // Creating a new page

        page.navigate("https://testkru.com/Elements/Buttons");

        // locating element
        Locator thirdButton = page.locator("//div[@id='content']//button").nth(2);
        System.out.println(thirdButton.innerText()); // printing the text

        // closing the instances
        browser.close();
        playwright.close();
    }

}

Output –

Left click on me

The text of the third button was retrieved, confirming that our locator worked.

We hope that you have liked this article. If you have any doubts or concerns, please write to us in the comments or email us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *