Xpath with elements containing specific text
To select an <a> element that contains an href attribute with the text "test" using XPath, you can use the contains() function.
Here’s the XPath expression to select an <a> element where the href contains the substring "test":
//a[contains(@href, 'test')]
Explanation:
//a: Selects all<a>elements in the document.contains(@href, 'test'): Matches only those<a>elements where thehrefattribute contains the string"test".
Example HTML:
<a href="https://example.com/test-page">Link 1</a>
<a href="https://example.com/sample">Link 2</a>
<a href="https://example.com/testing">Link 3</a>
XPath Query:
//a[contains(@href, 'test')]
Result:
This XPath will select the following <a> elements from the example HTML:
<a href="https://example.com/test-page">Link 1</a>
<a href="https://example.com/testing">Link 3</a>
Additional Use Cases:
If you want to match the href that starts with "test", use the starts-with() function:
//a[starts-with(@href, 'test')]
If you want to match the entire href (i.e., it should be exactly "test"), you can use the = operator instead of contains():
//a[@href='test']