Playwright XPath Locators

A GPS system can guide a driver using street names, or it can guide using turn-by-turn directions from the starting point. XPath works like the second method, describing a path through the page's structure step by step until it reaches the target element.

Understanding the Page as a Tree

Every webpage organizes its content in a nested structure, similar to folders inside folders on a computer. XPath reads this structure and walks through it to locate an element, even one without any ID or class.

Page Structure as a Tree

html
 |-- body
      |-- div (main content)
           |-- form
                |-- input (email field)
                |-- button "Register"

Basic XPath Syntax

page.locator('//button[text()="Register"]');

The double slash means "search anywhere in the page." The square brackets add a condition, in this case matching a button showing the exact text "Register."

Finding an Element by Attribute

page.locator('//input[@name="email"]');

This line finds an input element with an attribute named "name" equal to "email," useful when no ID exists on that field.

Finding Partial Text Matches

page.locator('//button[contains(text(), "Add")]');

This matches any button containing the word "Add" anywhere in its text, catching labels like "Add to Cart" or "Add Item" with one flexible pattern.

Navigating Between Parent and Child Elements

page.locator('//div[@class="product-card"]//button');

This finds a button located anywhere inside a div with the class "product-card," useful when a repeated card layout contains several similar buttons across a page.

A Practical Example

A pricing page shows three plan cards, each with a "Choose Plan" button. XPath can target the button inside the card containing the text "Premium," even without any unique ID on that specific button.

page.locator('//div[contains(text(),"Premium")]/ancestor::div[@class="plan-card"]//button');

CSS Locators Versus XPath

CSS locators read faster and stay simpler for everyday cases. XPath handles situations CSS cannot, such as searching by visible text or moving upward from a child element to its parent.

Quick Practice Task

Find a button on any website that has no unique ID or class. Write an XPath expression that locates it using its visible text instead.

Key Takeaways

  • XPath locates elements using page structure, attributes, or visible text.
  • It works even when no ID or class exists on the target element.
  • XPath can navigate from a child element up to its parent container.
  • Use XPath for cases CSS selectors genuinely cannot handle.

Leave a Comment

Your email address will not be published. Required fields are marked *