Mala Mala - 7 months ago 29
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

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();

The text that I am trying to get is:


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')]"));


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( || (name === '')">
<div class="text-right ng-binding">45</div>
<div class="text-left ng-binding">
<span class="elemSym ng-binding">Se</span>

What should I do?


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')]