Skip to content
CodeKruPro

Write dynamic XPath with contains() and starts-with()

Automation taskEasy-MediumAsked in: Accenture, Capgemini, Infosys, TCS, Wipro

The most asked locator task: "The id changes on every load, like user_8273. Write an XPath that still finds it." starts-with() and contains() match only the stable part of a value or of the text, so the changing number no longer matters. Here, on a page of links, you find one link by part of its text and another by the start of its id.

XPath Functions - contains() and starts-with()

Video walkthrough

Watch on YouTube

XPath Functions

XPath provides functions for flexible matching:

  • contains(@attr, 'value') - attribute contains text
  • starts-with(@attr, 'value') - attribute starts with text
  • contains(text(), 'value') - element text contains text

Relevant HTML structure:

<a id="seleniumLink" href="...">Practice TextFields</a>
<a id="playwrightLink" href="...">Practice Buttons</a>
<a id="cypressLink" href="...">Practice Checkboxes</a>

Task:

  1. Navigate to https://testkru.com/Elements/Links
  2. Find link where text contains "TextFields" using XPath
  3. Print its full text
  4. Find link where ID starts-with "cypress" using XPath
  5. Print its full text

Expected output:

Contains 'TextFields': Practice TextFields
Starts with 'cypress': Practice Checkboxes
Read full tutorial on Codekru