Playwright XPath Selectors

Profile picture for user arilio666

XPath stands for XML Path. It is W3C recommended technique used to identify and navigate nodes in an XML document. In automation, we use XPath to find elements on a webpage. Like any other language, Playwright supports XPath Selector and all its techniques and functions.

XPath selectors are equivalent to calling Document.evaluate(), where evaluate() is a method of the Document interface that selects elements based on the XPath expression given in parameters. 

Note: XPath does not pierce shadow roots.

Table of Contents

  1. Syntax
  2. Examples
  3. Video Tutorial



Use the locator method, and inside single or double quotes, use your XPath selector or expression. A selector starting with a double forward slash (//) or double dots (..) is assumed to be an XPath selector. For example, Playwright converts '//html/body' to 'xpath=//html/body'. However, in some cases, like when you use a single forward slash / or single dot (.), you will get an error if you will not use xpath=.


For the demo, we will click on the search icon of programsbuzz using the XPath selector.

Xpath in Playwright

1. Without using xpath=

await page.locator("//button/i[contains(@class,'fa-search')]").click()

2. with xpath=, here xpath= is optional

await page.locator("xpath=//button/i[contains(@class,'fa-search')]").click()

3. with xpath mandatory

await page.locator("xpath=/html//button/i[contains(@class,'fa-search')]").click()

Here we are starting with single slash, you will get an error if you will remove xpath=.

4. Using XPath indexing

Here expression is starting with round bracket ( and xpath= is optional

await page.locator("(//button/i[contains(@class,'fa-search')])[1]").click()

Video Tutorial: XPath in Playwright