gpt4 book ai didi

java - 如何使用 Selenium 从不包括其子元素的元素中获取文本

转载 作者:行者123 更新时间:2023-12-02 07:47:26 25 4
gpt4 key购买 nike

HTML

<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 上对此进行了测试,它有效。

/**
* 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"))));

关于java - 如何使用 Selenium 从不包括其子元素的元素中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39741076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com