Playwright Tutorial: Mastering Element Locators

Playwright Tutorial: Mastering Element Locators

Introduction

This article explores the various techniques Playwright offers for locating elements, including basic methods such as CSS selectors and text selectors, as well as more advanced filtering options and operators. These tools enable precise and efficient element selection, making Playwright a powerful choice for reliable web application testing.

Basic Locating

Locators in Playwright encapsulate methods to find and interact with elements on a webpage. Each time a locator is used for an action, it dynamically locates the most current DOM element, reducing test flakiness.

  • getByRole()

This locator targets elements based on their ARIA roles, such as buttons, checkboxes, or input fields. It accepts a value from the AriaRole enum and an optional second argument for additional role-specific options.

page.getByRole(AriaRole.HEADING);
page.getByRole(AriaRole.TEXTBOX, new Page.GetByRoleOptions().setName("billing address"));
page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setChecked(true));
page.getByRole(AriaRole.RADIO, new Page.GetByRoleOptions().setDisabled(true));
  • getByLabel()

Used to find input elements associated with a specific label, which is useful for forms.

page.getByLabel("Password");
page.getByLabel(Pattern.compile("(?i).*name.*"));
  • getByPlaceholder()

Targets inputs with a placeholder attribute, guiding users on what to enter.

page.getByPlaceholder("name@example.com");
page.getByPlaceholder(Pattern.compile("^[\\w.%+-]+@[\\w.-]+\\.[a-zA-Z]{2,}$"));
  • getByText()

Useful for locating non-interactive elements that contain specific text. Playwright normalizes whitespace, so you don’t need to worry about it.

page.getByText("Your Ultimate Test Automation Partner");
page.getByText("Ultimate Test Automation", new Page.GetByTextOptions().setExact(false));
page.getByText(Pattern.compile("Partner$"));
  • getByAltText()

Searches for or elements using the ‘alt’ attribute, which is reliable for images.

page.getByAltText("Parallel on Agents", new Page.GetByAltTextOptions().setExact(true));
page.getByAltText(Pattern.compile("^people"));
  • getByTitle()

Locates elements by their title attribute.

page.getByTitle("Automate the Planet Logo");
page.getByTitle(Pattern.compile("Logo$"));
  • getByTestId()

Targets elements by test IDs, which remain consistent even if the page content changes. Configure Playwright to recognize the attribute used as a test ID.

playwright.selectors().setTestIdAttribute("bellatrix-testid");
page.getByTestId("bellatrix-testid");
page.getByTestId(Pattern.compile("^testid"));
  • locator()

For more complex scenarios, you can use advanced CSS or XPath selectors.

page.locator("//img[@alt='people_image' and contains(@src, 'Forbes.jpeg')]");
page.locator("[id='logo']");

When using locators, it’s advisable to prepend them with “xpath=” or “css=” to ensure Playwright correctly interprets the selector type.

Filtering

Except the basic locating by one locator, one can specify even more detailed search.

Filter by Text

In Playwright, filtering by text can be particularly useful when you need to interact with elements that contain specific text or when you want to exclude elements that contain certain text. 

  • hasText

The setHasText method is used to specify the text that must be present in the matched elements. This is useful for ensuring you interact with the correct element when multiple elements may match a broader selector.

To filter elements that contain specific text, you can use the locator method combined with the hasText option.

Locator button = page.locator("button", new Locator.LocatorOptions().setHasText("Submit"));
button.click();

In this example, the locator method is used to find a button element that contains the text “Submit”. The setHasText method filters the elements to include only those that contain the specified text.

You can also filter by partial text.

Locator button = page.locator("button", new Locator.LocatorOptions().setHasText(Pattern.compile("Sub")));
button.click();

Here, the setHasText method uses a regular expression to match elements that contain the text “Sub” anywhere within the element.

  • hasNotText

The hasNotText option is used to specify the text that must not be present in the matched elements. This is useful for excluding elements that might interfere with the desired interaction.

To filter elements that do not contain specific text, you can use a combination of the locator method and a negative condition in your filtering logic.

Suppose you want to find a button that does not contain the text “Cancel”.

Locator button = page.locator("button").filter(new Locator.FilterOptions().setHasNotText("Cancel"));
button.click();

In this example, the filter method is used to exclude any button elements that contain the text “Cancel”. The setHasNotText method specifies the text that should not be present in the matched elements.

You can also filter by not having partial text.

Locator button = page.locator("button").filter(new Locator.FilterOptions().setHasNotText(Pattern.compile("Can")));
button.click();

Here, the setHasNotText method uses a regular expression to exclude elements that contain the text “Can” anywhere within the element.

Filter by Child/Descendant

Filtering by children or descendants in Playwright involves selecting elements based on the presence or absence of specific child elements. This can help ensure you are interacting with the correct parent element that has (or lacks) certain children

  • has

The has option is used to specify the child or descendant element that must be present in the matched elements. This helps ensure you interact with the correct parent element that has the desired children.

Suppose you want to find a div element that contains a span with the text “Child”.

Locator parentDiv = page.locator("div", new Locator.LocatorOptions().setHas(page.locator("span:has-text('Child')")));
parentDiv.click();

In this example, the locator method is used to find div elements that contain a span child with the text “Child”. The setHas method specifies the child element that must be present.

You can also filter by the presence of descendants with specific attributes.

Locator parentDiv = page.locator("div", new Locator.LocatorOptions().setHas(page.locator("input[type='text']")));
parentDiv.click();

Here, the locator method finds div elements that contain an input child with the type “text”. The setHas method specifies the child element with the desired attribute.

  • hasNot

The hasNot option is used to specify the child or descendant element that must not be present in the matched elements. This is useful for excluding parent elements that might interfere with the desired interaction.

Suppose you want to find a div element that does not contain a span child.

Locator parentDiv = page.locator("div").filter(new Locator.FilterOptions().setHasNot(page.locator("span")));
parentDiv.click();

In this example, the filter method is used to exclude any div elements that contain a span child. The setHasNot method specifies the child element that must not be present.

You can also filter by the absence of descendants with specific attributes.

Locator parentDiv = page.locator("div").filter(new Locator.FilterOptions().setHasNot(page.locator("input[type='password']")));
parentDiv.click();

Here, the filter method excludes div elements that contain an input child with the type “password”. The setHasNot method specifies the child element with the attribute that should not be present.

Operators

Operators in Playwright allow you to construct more complex locators by combining simpler locators. One common use case is to match elements that satisfy two (or more) conditions simultaneously. Another use case is to match elements that satisfy one of two (or more) conditions. We will look at them in the following sections.

Matching Simultaneously Two or More Conditions

The Locator class encapsulates the method and, which narrows down the search by stating additional conditions – locators.

page.getByRole(AriaRole.IMG).and(page.getByTitle("Automate The Planet Logo"));

Matching One of Multiple Conditions

The or() method in Playwright is used to create a locator that matches elements satisfying at least one of multiple conditions. This can be particularly useful when you want to interact with elements that could meet any one of several different criteria.

page.locator("button").and(page.locator(".btn-primary").or(page.locator("//*[text()=’Submit’]")));

As you can see from the example, you can combine the two operators.

Summary

This article delves into the powerful locator methods offered by Playwright, focusing on filtering techniques and combining locators for more precise web testing. We explored how to filter elements based on text, children, or attributes, and demonstrated advanced techniques such as using the or() method to handle multiple conditions. By mastering these methods, you can enhance the accuracy and reliability of your automated tests, ensuring your web applications function as intended. This guide is an essential resource for developers and QA engineers aiming to refine their testing strategies with Playwright.

For deeper insights, explore Playwright’s official documentation.

Related Articles

Resources, Web Automation Java

Most Complete Selenium WebDriver Java Cheat Sheet

As you know, I am a big fan of Selenium WebDriver. You can find tonnes of useful Java code in my Web Automation Java Series. I lead automated testing courses an

Most Complete Selenium WebDriver Java Cheat Sheet

Web Automation Java

Design Grid Control Automated Tests with Java Part 1

In the previous article, I showed you how to automate complex custom-tuned controls like a grid. In my article Automate Telerik Kendo Grid with WebDriver and Ja

Design Grid Control Automated Tests with Java Part 1

Web Automation Java

Deep Dive into JUnit Assertions with WebDriver and Custom Assertions

JUnit assertions are a cornerstone of Java testing, enabling developers to write tests that verify code behavior. In this article, we'll explore the various JUn

Deep Dive into JUnit Assertions with WebDriver and Custom Assertions

Web Automation Java

Shadow DOM: Locating Elements with XPath Workaround

In this post, we will go through the basics of shadow DOM, its use, benefits, and constraints, and we will analyse the solution for them. As an Automation Engin

Shadow DOM: Locating Elements with XPath Workaround

Web Automation Java

Playwright Tutorial: IFrame and Shadow DOM Automation

In this post, we will go through the basics of IFrames and Shadow DOM, and we will learn the strategies of automating these complex HTML structures with Playwri

Playwright Tutorial: IFrame and Shadow DOM Automation

Web Automation Java

Design Grid Control Automated Tests with Java Part 2

In my previous article, Design Grid Control Automated Tests Part 1, I started this mini-series about writing decent grid control automated tests. In this second

Design Grid Control Automated Tests with Java Part 2
Anton Angelov

About the author

Anton Angelov is Managing Director, Co-Founder, and Chief Test Automation Architect at Automate The Planet — a boutique consulting firm specializing in AI-augmented test automation strategy, implementation, and enablement. He is the creator of BELLATRIX, a cross-platform framework for web, mobile, desktop, and API testing, and the author of 8 bestselling books on test automation. A speaker at 60+ international conferences and researcher in AI-driven testing and LLM-based automation, he has been recognized as QA of the Decade and Webit Changemaker 2025.