Mala Mala - 5 months ago 12
Java Question

How to get text inside depth div tag with Selenium

I am trying to get the text content of the items inside the following 2

div
elements. It work using absolute path:

element = driver.findElement(By.xpath(".//*[@id='page-wrapper']/section/section/div/div[2]/section/div/div/div/div[45]"));
data = element.getText();
System.out.println(data);


The text that I am trying to get is:


45
Se
Selenium


I am trying to get text using relative XPath, but it always fails.

I am trying use this combination:

element = driver.findElement(By.xpath("//div[contains(@class,'elemBox noclaim noclaim-tt') and contains(text(),'45')]"));


or

element = driver.findElement(By.xpath("//div[contains(@class,'elemBox noclaim noclaim-tt')]/div[contains(text(),'45')]"));


but still failed.

I have HTML code like this:

<div class="elemBox noclaim noclaim-tt text-right m-t-lg animated-add pulse-add animated pulse animated-add-active pulse-add-active" >
<div class="" ng-show="(filterTool(elementName.name)) || (name === '')">
<div class="text-right ng-binding">45</div>
<div class="text-left ng-binding">
<span class="elemSym ng-binding">Se</span>
<br/>
Selenium
</div>
</div>




What should I do?

Answer

By using contains(text(),'45'), only the first direct-child text node will be evaluated. This is the reason you attempted XPath failed to find the div; because the text '45' is nested 2 levels from the outer div :

//div[contains(@class,'elemBox noclaim noclaim-tt') and contains(div/div/text(),'45')]

Or you might want to try using . instead of text to evaluate the entire texts within the outer div as opposed to evaluating only first direct-child text node :

//div[contains(@class,'elemBox noclaim noclaim-tt') and contains(.,'45')]