问题描述
我正在使用 selenium 通过 xpath 在我的网页上获取一些文本.
I'm using selenium to get some text on my webpage using xpath.
页面标签结构如下——
<span id="data" class="firefinder-match">
Seat Height, Laden
<sup>
<a class="speckeyfootnote" rel="p7" href="#">7</a>
</sup>
</span>
如果我使用以下代码 -
If I use the following code -
driver.findElement(By.xpath("//span[@id='data']")).getText();
我得到的结果 = Seat Height, Laden 7
但我想避免阅读 <sup>
标签中的文本并获取result 座椅高度,满载
But I want to avoid reading the text within the <sup>
tags and get theresult Seat Height, Laden
请告诉我可以使用哪个 xpath 表达式来获得所需的结果.
Please let me know which xpath expression I can use to get my desired result.
推荐答案
我不知道在 Selenium 中有什么方法可以做到这一点,所以这是我的 JS 解决方案.这个想法是获取元素的所有子元素(包括文本节点),然后只选择文本节点.您可能需要添加一些 .trim()
(或 JS 等效项)调用以去除不需要的空格.
I don't know about any way to do this in Selenium, so there's my JS solution. The idea is to get all children of the element (including the text nodes) and then select only the text nodes. You might need to add some .trim()
(or JS equivalent) calls to get rid of unneeded spaces.
完整代码:
WebElement elem = driver.findElement(By.id("data"));
String text;
if (driver instanceof JavascriptExecutor) {
text = ((JavascriptExecutor)driver).executeScript(
"var nodes = arguments[0].childNodes;" +
"var text = '';" +
"for (var i = 0; i < nodes.length; i++) {" +
" if (nodes[i].nodeType == Node.TEXT_NODE) {" +
" text += nodes[i].textContent;" +
" }" +
"}" +
"return text;"
, elem);
}
为了更好的可读性,只有 JS.
And just the JS for better readability.
var nodes = arguments[0].childNodes;
var text = '';
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType == Node.TEXT_NODE) {
text += nodes[i].textContent;
}
}
return text;
这篇关于使用 selenium webdriver(xpath) 读取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!