小编dys*_*nal的帖子

在dom中查找包含带有xpath的单词的文本节点

我需要从html文件中的节点中提取文本,我正在尝试使用XPath和Javascript.

必需条件是文本必须包含特定单词.

让我们以下面的html文件为例:

<html>
    <body>
        <p>
            Hi, try to extract the word username here and here <b>username</b>
        </p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

并尝试使用此表达式从包含"username"一词的文本节点中获取文本:

var search = document.evaluate('//*[contains(child::text(), \"username\")]/child::text()', document, null, XPathResult.ANY_TYPE, null);
Run Code Online (Sandbox Code Playgroud)

通过搜索迭代我发现了所需的结果,但也发现了不需要的对象:

["Hi, try to extract the word username here and here", Text, "username"]
Run Code Online (Sandbox Code Playgroud)

其中Text是一个Object,其textContent只是回车符号(我正在使用谷歌Chrome控制台).这个对象来自哪里?

任何人都可以提供一个更精确的XPath表达式来排除那些对象,还是应该在我的代码中将它们排除?

理想的搜索应该是:

["Hi, try to extract the word username here and here", "username"]
Run Code Online (Sandbox Code Playgroud)

谢谢大家!

javascript xpath dom

5
推荐指数
1
解决办法
6831
查看次数

标签 统计

dom ×1

javascript ×1

xpath ×1