如何使用Selenium从不包含其子元素的元素获取文本 [英] How to use Selenium get text from an element not including its sub-elements

查看:102
本文介绍了如何使用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"))));

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

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