Find Web Elements by XPath in Playwright

 

In Playwright Java, you can find elements using XPath by using the locator() method with the XPath expression prefixed by "xpath=".












Example: Find an element by XPath in Playwright Java.

Let’s take https://example.com as the sample website and find the <h1> element using XPath.


import com.microsoft.playwright.*;

public class XPathExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
      Page page = browser.newPage();

      // Navigate to example website
      page.navigate("https://example.com");

      // Find element using XPath
      Locator heading = page.locator("xpath=//h1");

      // Print the heading text
      System.out.println("Heading: " + heading.textContent());
    }
  }
}


XPath Syntax Recap

  • //tagname: Selects all elements with the tag name.

  • //*[@attribute='value']: Selects elements by attribute.

  • //div[contains(text(),'Sample')]: Selects elements that contain specific text.




Another Example with Attribute XPath

Locator element = page.locator("xpath=//*[@id='username']");




This selects an element with the id="username".



No comments:

Post a Comment