如何使用selenium从不包含它的子元素的元素中获取Text

Dal*_*ale 4 java selenium

HTML

<div id='one'>
    <button id='two'>i am button</button>
    <button id='three'>i am button</button>
    i am div
</div>
Run Code Online (Sandbox Code Playgroud)

driver.findElement(By.id('one')).getText();
Run Code Online (Sandbox Code Playgroud)

Jef*_*ffC 10

我已经看到这个问题在最后一年左右会弹出几次,我想尝试写这个功能......所以你走了.它接受父元素并删除每个子元素的textContent,直到剩下的是textNode.我已经在你的HTML上测试了这个并且它有效.

/**
 * Takes a parent element and strips out the textContent of all child elements and returns textNode content only
 * 
 * @param e
 *            the parent element
 * @return the text from the child textNodes
 */
public static String getTextNode(WebElement e)
{
    String text = e.getText().trim();
    List<WebElement> children = e.findElements(By.xpath("./*"));
    for (WebElement child : children)
    {
        text = text.replaceFirst(child.getText(), "").trim();
    }
    return text;
}
Run Code Online (Sandbox Code Playgroud)

你打电话给它

System.out.println(getTextNode(driver.findElement(By.id("one"))));
Run Code Online (Sandbox Code Playgroud)

  • 我已经说过这不是一般情况下的解决方案。所以我只是很好奇......当这个页面上的其他答案都不适用于一般情况时,为什么你如此关注我和我的答案?你还没有对他们投反对票或评论。您提供的两个答案不起作用,另一个是从另一个用户复制的,但仍然不起作用。我只是在 Chrome 上运行了你的所有案例和 OP,但没有一个成功。 (2认同)