Test Plans into Automation

Navigation

Wrangle XPath to Locate Nodes that Contains Text

XPath is a powerful tool used in testing to locate specific nodes within the DOM. One common use case is locating nodes that contain specific text. This allows testers to efficiently pinpoint elements on a webpage without relying solely on element attributes. By mastering the art of wrangling XPath, testers can enhance their test automation capabilities and ensure accurate and reliable test results.

Table of Contents

Using Contains and Starts-With Method

To locate nodes that contain specific text using XPath, you can utilize the contains() or starts-with() methods. The contains() method allows you to search for a partial match within the text of a node, while the starts-with() method enables you to find nodes with text that starts with a specific value. To use the contains() method, you can write the XPath expression like //element[contains(text(),'your_text')]. This will return all elements that contain ‘your_text’ within their text content. For the starts-with() method, the XPath expression should be //element[starts-with(text(),'your_text')]. This will match all elements whose text content starts with ‘your_text’. By applying these methods in your XPath queries, you can easily locate nodes that contain or start with specific text within the DOM

Examples

//h1[contains(text(), “My Calendar”)]

//h1[starts-with(text(), “My”)]

//h1[text() = “My Calendar”)]

//h1[text() = “My Calendar”)]/following-sibling::h2[contains(text(), “January”)]

Further Reading

Helpful Tools

Test your XPath in Chrome or Firefox Javascript Console

$x(“my xpath”)

Here’s an example of grabbing the Google logo via the Javascript Console. Just type your query in there and press enter to see the results.

Locating the Google Logo using XPath and Chrome Dev Tools

Finding XPath of element in Chrome/Firefox DOM Inspector

You can also copy the full XPath of an element via the DOM inspector. Just right click on the element and choose Copy XPath.

Copying XPath from Chrome Dev Tools
Turn Manual Test Plans into a robot that completes your tests in a fraction of the time.
  • No coding or recording required
  • Copy/paste your existing test plans
  • Trigger manually, on a schedule or via CI/CD
Testing Taxi test writer

Navigation

Share the Post:

Related Posts

Turn Manual Test Plans into a robot that completes your tests in a fraction of the time.
  • No coding or recording required
  • Copy/paste your existing test plans
  • Trigger manually, on a schedule or via CI/CD
Testing Taxi test writer