Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath query searching for an element with specific text

Tags:

xml

xpath

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?

like image 980
Marcus S. Zarra Avatar asked Sep 29 '08 04:09

Marcus S. Zarra


People also ask

How do I search for text in XPath?

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.

What is text () in XPath?

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.

How use contains keyword in XPath?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]

How will you write XPath if the tag has only text?

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.


2 Answers

//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

like image 116
A. Rex Avatar answered Sep 22 '22 10:09

A. Rex


Valid option is also:

//span[contains(.,'Test')]
like image 40
Jackson Lee Avatar answered Sep 26 '22 10:09

Jackson Lee