![](/img/trans.png)
[英]How to get anchor tag href and anchor tag text inside a div using Selenium in Java
[英]How to get text inside depth div tag with Selenium
我正在嘗試獲取以下2個div
元素內各項的文本內容。 它使用絕對路徑工作:
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);
我想得到的文字是:
45 Se Selenium
我正在嘗試使用相對XPath獲取文本,但是它總是失敗。
我正在嘗試使用此組合:
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>
我該怎么辦?
通過使用contains(text(),'45')
,將僅評估第一個直接子文本節點。 這就是您嘗試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')]
我認為,您不需要在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']"));
....如果您確實需要找到具有價值的元素,
textRightElement = driver.findElement(By.xpath("//div[text()='45']"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.