How To Find Elements by XPath in Playwright

Explore how XPath can help you find elements in Playwright, boosting your web automation process. Start mastering this powerful method today!

Last updated: 28 July 2026 8 min read

Key Takeaways

  • XPath helps you locate elements through attributes and text when simpler locators are not enough.
  • Playwright handles most waiting automatically so you usually do not need extra waits before every interaction.
  • Built-in locators should be your first choice while XPath works well for elements that are harder to target.

If you’re not new to Playwright, you would know finding the right element has to be the most important part of any Playwright test. But not every element has a clear ID or attribute you can use. When selectors become difficult to write or break after page changes, your tests can quickly become harder to maintain.

XPath gives you another way to find these elements. You can use it to locate elements based on their position, attributes, text, or relationship with other elements on the page.

Through this article, I’ll show you how to use XPath in Playwright with practical examples. You’ll also learn when to use it and how it compares with other locator options.

The Fundamental Syntax

XPath uses path expressions to find elements within the DOM. The syntax tells Playwright where to look and what conditions an element needs to match.

A simple XPath expression looks like this:

//button

Here, // searches for matching elements anywhere in the document and, button specifies the element you want to find. You can make the expression more specific by adding attributes or other conditions:

//button[@type='submit']

The main parts of XPath syntax include:

  • Axes: Define the relationship between elements such as parent, ancestor, child, or following-sibling.
  • Predicates: Add conditions to narrow down the elements you want to select. They are written inside square brackets [].
  • Operators: Compare values or combine conditions using operators such as =, !=, and, and or.

Once you understand these building blocks, you can combine them to locate elements that may be difficult to target with a simple selector.

Using XPath With Playwright Locators

In Playwright, you can use XPath expressions directly with the locator() method. Once Playwright finds the matching element, you can work with it like any other locator to click it, enter text, or perform assertions.

Here is a simple example:

const submitButton = page.locator('xpath=//button[text()="Submit"]');

await submitButton.click();

The xpath= prefix tells Playwright to treat the value that follows as an XPath expression. You can also leave out the prefix when the selector starts with // or .., as Playwright can detect XPath selectors automatically:

const submitButton = page.locator('//button[text()="Submit"]');

How Playwright Supports XPath Locator API Basics and Syntax Terminal

How Playwright Supports XPath Locator API Basics and Syntax Localhost

Playwright locators are also designed to wait for elements before performing actions. This means you usually do not need to add separate waits before clicking or interacting with an element.

XPath can be useful when you need to locate an element through its position or relationship with other elements in the DOM. However, for most tests, Playwright recommends user-facing locators such as getByRole() and getByLabel() because they are generally less dependent on the page structure.

A Step-by-Step Element Selection Workflow

Using XPath in a Playwright test follows the same basic flow as working with any other locators. You can create an expression that identifies the element and pass it to locator() before performing the required action.

Here is how the process works:

  • Launch the browser: Start your Playwright browser and create a new page.
  • Open the page: Use page.goto() to navigate to the application you want to test.
  • Write the XPath expression: Identify the element using its text, attributes, or relationship with other elements.
  • Create the locator: Pass the XPath expression to page.locator().
  • Interact with the element: Use the locator to click, fill, or verify the element.

For example, the following test locates a link with the text Learn More and clicks it:

const link = page.locator('//a[text()="Learn More"]');

await link.click();

If the page contains several similar links, you can make the XPath more specific by adding another condition:

const link = page.locator('//a[@class="learn-more" and text()="Learn More"]');

await link.click();

Step by Step Finding Elements with XPath in Playwright Terminal

Step by Step Finding Elements with XPath in Playwright Localhost

Ultimately, choose an XPath that identifies the intended element without depending too heavily on its exact position in the DOM. This makes the locator easier to maintain when the page structure changes.

Handling Elements That Load or Change Dynamically

When testing, some elements appear only after an API response or a user action. If your test tries to interact with an element before it is ready, the step may fail.

Before performing actions such as click(), it checks whether the target element meets the required actionability conditions. In many cases, this means you do not need to add a separate wait.

For example:

const submitButton = page.locator('//button[text()="Submit"]');

await submitButton.click();

Playwright waits for the button to become actionable before clicking it. There are cases where you may need to wait for a specific state without immediately performing an action. You can use waitFor() for this:

await page

  .locator('//button[text()="Submit"]')

  .waitFor({ state: 'visible' });

Waiting Synchronization Dealing with Dynamic Elements When Using XPath Terminal

Waiting Synchronization Dealing with Dynamic Elements When Using XPath Localhost

This waits until the matching button is visible before the test continues.

Talk to an Expert

When XPath May Not Be the Best Choice

Although XPath is useful when you need to navigate element relationships, it does not need to be your first choice for every element.

  • There is a simpler option: If you can find the element with getByRole(), getByLabel(), or another user-facing locator, use that instead. These locators are usually easier to read and maintain.
  • Your XPath is getting too long: A locator that depends on several levels of the DOM can break when the page structure changes. If the expression is difficult to understand at a glance, look for a more stable attribute or relationship.
  • You are relying on exact positions: Expressions such as div[2]/button[1] depend heavily on the current page structure. Adding or moving an element can cause the test to target the wrong one.
  • The text changes often: Locating an element by exact text can be unreliable when the content is dynamic or frequently updated. A role, label, or test ID may give you a more stable target.
  • A test ID is already available: If your application provides dedicated attributes such as data-testid, you can use getByTestId() instead of building a complex XPath expression.

Cross-Browser Tests with XPath-Based Selectors

When working with automated tests across different browsers and environments, BrowserStack Automate offers a powerful solution to ensure cross-browser compatibility for XPath-based selectors. With BrowserStack Automate, you can run your Playwright scripts on real devices and browsers in the cloud, ensuring that your XPath selectors work consistently across various configurations.

This cloud-based testing tool allows you to:

  • Run tests on different browsers (Chrome, Firefox, Safari) simultaneously.
  • Validate XPath-based selectors on real devices and operating systems.
  • Quickly debug any issues by inspecting logs and browser videos from the test sessions.

BrowserStack’s comprehensive platform makes it easy to scale your testing infrastructure without managing physical devices, which is invaluable for teams looking to maintain robust, cross-browser compatibility with XPath-based testing.

Try BrowserStack Automate

Best Practices for Writing Resilient XPath Locators in Playwright

To make your XPath selectors more reliable and less prone to failure, follow these best practices:

  • Use relative XPath: Avoid absolute XPath as it is more brittle and depends on the full structure of the DOM. Use relative XPath to target elements dynamically.
  • Avoid relying on dynamic attributes: If possible, use stable attributes like id, name, or data-* attributes that are less likely to change over time.
  • Use predicates for better filtering: Instead of just selecting an element, refine your XPath with predicates (e.g., //input[@type=’text’]), ensuring more precise selections.
  • Test and maintain XPath expressions: Regularly check your XPath selectors, especially when the page structure changes.

Conclusion

The best locator is usually the one that gets the job done without making your tests harder to understand. Playwright’s built-in locators will cover most situations but XPath is handy when an element is tricky to reach.

You do not need to choose one and stick with it everywhere. Start simple and bring in XPath when the page structure actually calls for it. That way, your tests stay readable and are much easier to fix when the application changes.

Version History

  1. Jul 24, 2026 Current Version

    Covered new sections on key takeaways and references, along with incorporating code for each scenario.

    Yashraj Shrivastava
    Reviewed by Yashraj Shrivastava Product Manager
Tags
Playwright
Abdul Qadir Khan
Abdul Qadir Khan

Senior Automation Expert

Abdulqadir Khan is a quality engineering professional with 11+ years of experience in test automation and software testing. He focuses on building scalable automation solutions and enabling teams to accelerate software delivery while maintaining high quality standards.

Automation Tests on Real Devices & Browsers
Seamlessly Run Automation Tests on 3500+ real Devices & Browsers