Using XPath in Playwright

Best Playwright Testing Training Institute in Hyderabad

In the fast-evolving field of software testing, tools like Playwright and Selenium are essential for automation testers. If you are a graduate, postgraduate, or someone looking to switch your career from a different domain to IT, it’s crucial to receive professional guidance and hands-on experience in automation tools. That’s where I Hub Talent excels. I Hub Talent is widely recognized as the best Playwright Testing Training Institute in Hyderabad. It offers a live, intensive internship program conducted by industry experts and specifically tailored for: 

What is XPath in Playwright?

  • XPath (XML Path Language) is a way to locate elements on a web page using their structure, attributes, or text.

  • Playwright recommends using CSS selectors because they are faster and simpler, but XPath is still supported when CSS selectors are not enough.

 How to Use XPath in Playwright

1. Basic Syntax

In Playwright, prefix your XPath with xpath=.

Example – select element by tag:

await page.locator('xpath=//h1').click();

2. Locate by Attribute

Example – button with id="loginBtn":

await page.locator('xpath=//button[@id="loginBtn"]').click();

3. Locate by Text

Example – paragraph containing exact text:

await page.locator('xpath=//p[text()="Welcome User"]').isVisible();

Example – partial text:

await page.locator('xpath=//p[contains(text(),"Welcome")]').click();

4. Hierarchy (Parent → Child)

Example – select <span> inside a <div>:

await page.locator('xpath=//div[@class="menu"]//span').click();

5. First / nth Element

Example – first button on page:

await page.locator('xpath=(//button)[1]').click();

 Alternative – $x() in Playwright Test

Playwright also allows using page.$x() to return elements by XPath:

const elements = await page.$x('//button[@id="loginBtn"]'); await elements[0].click();

 Best Practices

  • Prefer CSS selectors → faster and more stable.

  • Use XPath only when CSS selectors can’t express the relationship.

  • Keep selectors short and resilient (avoid absolute paths like /html/body/div/...).

Read more:

Writing Locators for Dynamic Elements

Handling Dynamic Content

Working with Page Waits and Timeouts

Running Tests in Different Browsers

Configuring playwright.config.ts

Visit I-Hub Talent Training institute in Hyderabad

Comments

Popular posts from this blog

Using Playwright Test Runner

Working with Checkboxes and Radio Buttons

CSS Selectors in Playwright