简体   繁体   English

如何在不使用contains()和xpath的情况下从标签中检索特定文本?

[英]How to retrieve specific text from a tag without using contains() and xpath?

<div>
    <label1>Hulk</label1>
    <label2>Ironman</label2>
Thor
</div>

How do I get only Thor text without using contains in xpath ? 如何在不使用xpath中包含的情况下仅获取Thor文本?

If I try getting text of div it would give me all the 3 (Hulk, Ironman, Thor) but I want only Thor. 如果我尝试获取div的文本,它将给我全部3个(绿巨人,钢铁侠,雷神),但我只想要雷神。

To extract the text Thor without using contains in xpath you can use either of the following solutions: 要在不使用xpath中包含内容的情况下提取文本Thor ,可以使用以下解决方案之一:

  • xpath : xpath

     String myText = driver.findElement(By.xpath("//div[not(@label)]")).getText(); 
  • cssSelector : cssSelector

     String myText = driver.findElement(By.cssSelector("div:not(label)")).getText(); 
  • Using JavaScriptExecutor 使用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(); 

Note : Ensure that xpath as //div[not(@label)] and cssSelector as div:not(label) resembles to a unique element on the HTML DOM. 注意 :确保xpath作为//div[not(@label)]cssSelector作为div:not(label)与HTML DOM上的唯一元素相似。

您可以尝试以下提到的路径吗?

/div/text()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM