Find elements using XPath selectors in Playwright Java

XPath is a powerful and versatile language for locating elements within web pages. In the world of web automation, understanding XPath and its usage can greatly enhance your ability to locate elements with precision and reliability. This article will dive into locating elements using XPath in Playwright Java.

We have a detailed post on Xpath that explains the different types of Xpaths and how to write them for an element. We encourage you to read it to gain a clear understanding of Xpath.

Now, let’s start locating or locating the element by using the XPath expressions.

Playwright provides various methods to find elements using XPath –

  • querySelector() method
  • querySelectorAll() method
  • locator() method

We will not be discussing the querySelector() and querySelectorAll() methods, as they return an ElementHandle object that is now deprecated according to Playwright’s documentation. Instead, we will solely focus on using the locator() method to find the elements.

Syntax of locating element using locator() method and XPath expression
Locator locator = page.locator(xpath_epxression)
Code Example

Let’s see things with an example.

We will locate the below-highlighted element and get the text written on the button. You can find this element on our playground website.

left click button element

By inspecting the element, we can reveal its DOM and use it to create an XPath expression.

DOM of the left element

There are various methods to generate XPath, such as utilizing the name or id attribute along with their respective values.

//button[@name = 'leftClick'] 

or

//button[@id = 'leftClick']
Launching the browser and making the BrowserContext
		Playwright playwright = Playwright.create();
		Browser browser = playwright.chromium().launch();

		// creating a BrowserContext
		BrowserContext browserContext = browser.newContext();
Navigating to the URL
		// creating the page
		Page page = browserContext.newPage();
		
		// Navigating to the URL
		page.navigate("https://testkru.com/Elements/Buttons");
Now, locate the element using XPath
Locator buttonLocator = page.locator("//button[@name='leftClick']");
Get the text written on the button
System.out.println("Text written on the button: " + buttonLocator.textContent());

Combining all the code fragments into a single program.

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class CodekruTest {

	public static void main(String[] args) {

		Playwright playwright = Playwright.create();
		Browser browser = playwright.chromium().launch();

		// creating a BrowserContext
		BrowserContext browserContext = browser.newContext();

		// creating the page
		Page page = browserContext.newPage();

		// Navigating to the URL
		page.navigate("https://testkru.com/Elements/Buttons");

		Locator buttonLocator = page.locator("//button[@name='leftClick']");

		System.out.println("Text written on the button: " + buttonLocator.textContent());

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

	}

}

Output –

Text written on the button: Left click on me

The program successfully retrieved the text written on the button, which was located using an XPath expression.

Now, we have located an element, but one must know a few other basic points that are necessary while using the locator() method to locate the element.

What if the XPath expression matches two or more elements?

If we use the locator() method on such an XPath which is matching with two or more elements, then we will get the below exception –

Exception in thread "main" com.microsoft.playwright.PlaywrightException: Error {
  message='Error: strict mode violation: locator("xpath=//input[@id='firstName']") resolved to 2 elements:

There are multiple methods to address this type of exception, and the approach taken will vary based on your specific needs.

  • Get the first matching element
  • Get the last matching element
  • Get the nth matching element
  • Or, Get all elements

We have one such example present at the “https://testkru.com/Elements/TextFields” page, where an XPath ( //input[@id='firstName'] ) matches two elements.

XPath matching two elements
Get the first matching element

Locator provides a first() method which can return the first matching element.

Locator locator = page.locator("//input[@id='firstName']").first();
Get the last matching element

Similarly, we have a last() method that returns the last matching element.

Locator locator = page.locator("//input[@id='firstName']").last();
Get the nth matching element

In some cases, XPath may match more than two elements. In such situations, Playwright offers the nth() method, which enables us to choose the specific element we want from the multiple matches.

To access a specific element, we can use the nth() method and pass the element’s index as an argument. It’s important to note that the indexing is zero-based, meaning the first element has an index of 0. Therefore, to access the first element, we should pass 0 as the index in the nth() method.

Locator locator = page.locator("//input[@id='firstName']").nth(0);
Get all matching elements

We can also get all matching elements using the all() method and then build logic to iterate over them and perform desired actions. all() method returns a List.

List<Locator> locators = page.locator("//input[@id='firstName']").all();

 We hope that you have liked the article. If you have any doubts or concerns, please write to us in the comments or mail 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 *