如何在不使用contains()和xpath的情况下从标签中检索特定文本? [英] How to retrieve specific text from a tag without using contains() and xpath?
本文介绍了如何在不使用contains()和xpath的情况下从标签中检索特定文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<div>
<label1>Hulk</label1>
<label2>Ironman</label2>
Thor
</div>
如何在不使用xpath包含内容的情况下仅获取Thor文本?
How do I get only Thor text without using contains in xpath ?
如果我尝试获取div文本,它将给我全部3个(绿巨人,钢铁侠,雷神),但我只想要雷神.
If I try getting text of div it would give me all the 3 (Hulk, Ironman, Thor) but I want only Thor.
推荐答案
要提取文本 Thor 而不在xpath中使用包含,您可以使用以下任一解决方案:
To extract the text Thor without using contains in xpath you can use either of the following solutions:
-
xpath
:
String myText = driver.findElement(By.xpath("//div[not(@label)]")).getText();
cssSelector
:
String myText = driver.findElement(By.cssSelector("div:not(label)")).getText();
使用 JavaScriptExecutor
WebElement myElement = driver.findElement(By.xpath("//div[@attribute='value']")); //replace the pseudo attribute with actual attribute
String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].lastChild.textContent;', myElement).toString();
注意:确保 xpath 为//div [not(@label)]
和 cssSelector 为 div:not(label)
类似于HTML DOM上的唯一元素.
Note: Ensure that xpath as //div[not(@label)]
and cssSelector as div:not(label)
resembles to a unique element on the HTML DOM.
这篇关于如何在不使用contains()和xpath的情况下从标签中检索特定文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文