Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath //div[contains(text(), 'string')] fails to select divs containing 'string'

Tags:

html

xpath

This is the HTML code:

<div>  <span></span>  Elangovan  </div> 

I want to write an XPath for the div based on its contained text. I tried

//div[contains(text(),'Elangovan')] 

but this is not working.

like image 952
Elangovan S Avatar asked Nov 29 '14 23:11

Elangovan S


People also ask

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 find XPath text contains?

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

How do I add text to XPath?

Using XPath- text() method, we can write the Java code along with the dynamic XPath location as: findElement(By. xpath("//*[text()='Google offered in')]"));


1 Answers

Replace text() with string():

//div[contains(string(), "Elangovan")] 

Or, you can check that span's following text sibling contains the text:

//div[contains(span/following-sibling::text(), "Elangovan")]  

Also see:

  • Difference between text() and string()
like image 144
alecxe Avatar answered Sep 25 '22 00:09

alecxe