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.
