首页 > 解决方案 > 你如何找到没有重复的顶级文本节点

问题描述

我正在使用 R (rvest) 从不同站点抓取文章,这些文章通常以不同的方式构建,并希望提取所有 html 节点(不重复),其后代包含使用 xpath 的一些文本。

简化后,结构可能类似于(没有为可读性而引入的空格):

<html>
<body>
    <a name="SomeMarker">
            <font style="FONT-SIZE: 12pt;"><b>Sports article</b></font>
    </a>
<div>
<b>This is possibly an article heading</b>
<font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font
<font style="FONT-SIZE: 10pt;"> It could have <i><b>interesting tags</b></i> embedded in the text</font>
</div>

<p id="SomeId"><b>This is another article heading</b>
    <font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article</font>
    <p><font style="FONT-SIZE: 10pt;"> It could have further <i><b><u>interesting tags</u></b></i> embedded in the text</font></p>
</p>

</body>
</html>

我尝试了几种不同的 xpath——但它们似乎总是选择重复的节点

"//a/following::*//*[text()]"
"//a/following::*/*[normalize-space(text())]"
"//a/following::*/*[normalize-space(text())]/parent::*"

等等——但所有这些都会导致文本节点的各种排列

目前,我得到了很多重复的节点,例如:

[1] <div>\n<b>This is possibly an article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font><font style="FONT-SIZE: 10pt;"> It could have <i><b>interes ...
[2] <font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font>
[3] <i><b>interesting tags</b></i>
[4] <p id="SomeId"><b>This is another article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article.</font></p>\n
[5] <font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article.</font>
[6] <p><font style="FONT-SIZE: 10pt;"> It could have further <i><b><u>interesting tags</u></b></i> embedded in the text</font></p>
[7] <b><u>interesting tags</u></b>

首选结果是仅获取其后代包含某些文本的顶级节点,即在上述情况下:

[1] <div><b>This is possibly an article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font><font style="FONT-SIZE: 10pt;"> It could have <i><b>interesting tags</b></i> embedded in the text</font></div>
[2] <p id="SomeId"><b>This is another article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article.</font><p><font style="FONT-SIZE: 10pt;"> It could have further <i><b><u>interesting tags</u></b></i> embedded in the text</font></p></p>  

我知道仅用于提取文本的 xpath —— 我实际上想要带有完整标签的 html 节点,因为我想在顶级节点上进行进一步处理(例如提取标题)。非常感谢。

标签: rxpath

解决方案


选项 1:使用以下兄弟姐妹::

//a/following-sibling:: [ [text()]]

选项 2:使用具有以下内容的父级::

//a/following:: [ [text()]][parent::body]


推荐阅读