如何使用selenium从不包含它的子元素的元素中获取Text [英] How to use selenium get Text from an element not including it's sub-element

查看:743
本文介绍了如何使用selenium从不包含它的子元素的元素中获取Text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

<div id='one'>
    <button id='two'>i am button</button>
    <button id='three'>i am button</button>
    i am 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"))));

这篇关于如何使用selenium从不包含它的子元素的元素中获取Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆