Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath: select div that contains class AND whose specific child element contains text

Tags:

xpath

With the help of this SO question I have an almost working xpath:

//div[contains(@class, 'measure-tab') and contains(., 'someText')] 

However this gets two divs: in one it's the child td that has someText, the other it's child span.

How do I narrow it down to the one with the span?

<div class="measure-tab">   <!-- table html omitted -->   <td> someText</td> </div>  <div class="measure-tab">  <-- I want to select this div (and use contains @class)   <div>     <span> someText</span>  <-- that contains a deeply nested span with this text   </div> </div> 
like image 851
Andrejs Avatar asked Aug 14 '16 13:08

Andrejs


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 class in XPath?

In addition to the preceding statement, Xpath can locate nearly all of the items on a web page. As a result, Xpaths can be used to find components that lack an id, class, or name.


1 Answers

To find a div of a certain class that contains a span at any depth containing certain text, try:

//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')] 

That said, this solution looks extremely fragile. If the table happens to contain a span with the text you're looking for, the div containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.

like image 142
nwellnhof Avatar answered Nov 25 '22 21:11

nwellnhof