如何使用Selenium从不包含其子元素的元素获取文本

如何使用Selenium从不包含其子元素的元素获取文本

问题描述:

<div id='one'>
    <button id='two'>I am a button</button>
    <button id='three'>I am a button</button>
    I am a div
</div>

代码

driver.findElement(By.id('one')).getText();

在过去大概一年左右的时间里,我曾多次看到此问题,我想尝试编写此函数...所以在这里你去.它接受父元素,并删除每个子元素的textContent,直到剩下的是textNode为止.我已经在您的HTML上对此进行了测试,并且可以正常工作.

I've seen this question pop up a few times in the last maybe year or so and I've wanted to try writing this function... so here you go. It takes the parent element and removes each child's textContent until what remains is the textNode. I've tested this on your HTML and it works.

/**
 * 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;
}

你叫它

System.out.println(getTextNode(driver.findElement(By.id("one"))));