Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath find text in any text node

Tags:

xpath

I am trying to find a certain text in any text node in a document, so far my statement looks like this:

doc.xpath("//text() = 'Alliance Consulting'") do |node|   ... end 

This obviously does not work, can anyone suggest a better alternative?

like image 411
dagda1 Avatar asked Feb 22 '11 05:02

dagda1


People also ask

How do I search for text in XPath?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

Can we use text () in XPath?

5) XPath Text() FunctionThe XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.

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.


1 Answers

This expression //text() = 'Alliance Consulting' evals to a boolean.

In case of this test sample:

<r>     <t>Alliance Consulting</t>     <s>         <p>Test string             <f>Alliance Consulting</f>         </p>     </s>     <z>         Alliance Consulting         <y>             Other string         </y>     </z> </r> 

It will return true of course.

Expression you need should evaluate to node-set, so use:

//text()[. = 'Alliance Consulting'] 

E.g. expression:

count(//text()[normalize-space() = 'Alliance Consulting']) 

against the above document will return 3.

To select text nodes which contain 'Alliance Consulting' in the whole string value (e.g. 'Alliance Consulting provides great services') use:

//text()[contains(.,'Alliance Consulting')] 

Do note that adjacent text nodes should become one after parser gets to the document.

like image 175
Flack Avatar answered Oct 01 '22 14:10

Flack