Given the following XML structure
<html>
<body>
<div>
<span>Test: Text2</span>
</div>
<div>
<span>Test: Text3</span>
</div>
<div>
<span>Test: Text5</span>
</div>
</body>
</html>
What is the best XPath query to locate any span
with text that starts with Test
?
text() and contains methods text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value. contains(): Similar to the text() method, contains() is another built-in method used to locate an element based on partial text match.
XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.
The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]
We will start to write XPath with //, followed by input tag, then we will use the select attribute, followed by its attribute name like name, id, etc, and then we will choose a value of attribute in single quotes. Here, (1 of 1) means exact match. It indicates that there is only one element available for this XPath.
//span[starts-with(.,'Test')]
References:
http://www.w3.org/TR/xpath/#function-starts-with
https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with
Valid option is also:
//span[contains(.,'Test')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With