2016-06-17 6 views
1

次の2 div要素のテキスト内容を取得しようとしています。私は相対XPathを使用してテキストを取得しようとしています深みのあるdivタグ内のテキストをSeleniumで取得する方法

 
45 
Se 
Selenium 

が、それは常に失敗します。

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

私が取得しようとしていますテキストがある:それは絶対パスを使用して動作します。
私はこの組み合わせの使用をしようとしています:

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

が、それでも失敗しました。

私はこのようなHTMLコードを持っている:

<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> 

私は何をすべきか?

答えて

2

、最初のダイレクト・チャイルド・テキスト・ノードのみが評価されます。これが、XPathがdivを見つけられなかった理由です。テキストは「45」は、外側divから2つのレベルのネストされているので:

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

それとも、評価のみ最初ダイレクトとは対照的に、外側div内全体のテキストを評価するために、テキストの代わりに.を使用しようとする場合があります子テキストノード:

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

私は// div [contains(@ class、 'elemBox noclaim noclaim-tt')を含み、(。、 '45')] を含んでいます。どうもありがとうございました :) – Mala

0

xpathの中にcontainsという単語を使用する必要はありません。

textRightElement = driver.findElement(By.xpath("//div[@class='elemBox noclaim noclaim-tt']/div[@class='text-right']")); 

やクラスtext-rightが一意である場合は、単に使用

textRightElement = driver.findElement(By.xpath("//div[@class='text-right']")); 

....あなたは本当にそれが価値だと要素を見つける必要がある場合は、contains(text(),'45')を使用することにより

textRightElement = driver.findElement(By.xpath("//div[text()='45']")); 
+0

は「text-右」は、他のdivタグに を使用しているので、私は唯一の「テキスト右」を使用することはできませんし、私は、[使用テキストことができるだけでなく、()=「45」 ]私は3つすべてが必要です:45、セとセレンのテキストが必要な要素の結果だけのポイント45のため。 お返事ありがとうございます。 – Mala

関連する問題