3
我需要从html文件中的节点中提取文本,并尝试使用XPath和Javascript。在dom中查找包含带xpath的单词的文本节点
所需条件是文本必须包含特定的词。
让我们通过实例的下一个HTML文件:
<html>
<body>
<p>
Hi, try to extract the word username here and here <b>username</b>
</p>
</body>
</html>
,并得到包含单词“用户名”这种表达从文本节点文本:
var search = document.evaluate('//*[contains(child::text(), \"username\")]/child::text()', document, null, XPathResult.ANY_TYPE, null);
迭代通过搜索我已经找到想要的结果,但也有不想要的对象:
["Hi, try to extract the word username here and here", Text, "username"]
其中文本是对象其textContent仅为回车符(我正在使用Google Chrome控制台)。这个对象来自哪里?
任何人都可以给出一个更精确的XPath表达式来排除这些对象,还是应该在我的代码中排除它们?
理想的搜索应该是:
["Hi, try to extract the word username here and here", "username"]
谢谢大家!
非常感谢!在提出我的问题之后,我已经看到了灯光并找到了解决方案,就像您发布的解决方案一样,但我无法解释为什么(2)会发生。现在我可以;)在简单的内部跳出双引号是我的错误,不需要,谢谢你的提示! – dysfuntcional