r - 你如何找到没有重复的顶级文本节点
问题描述
我正在使用 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 节点,因为我想在顶级节点上进行进一步处理(例如提取标题)。非常感谢。
解决方案
选项 1:使用以下兄弟姐妹::
//a/following-sibling:: [ [text()]]
选项 2:使用具有以下内容的父级::
//a/following:: [ [text()]][parent::body]
推荐阅读
- javascript - 如何处理 gapi savetodrive src 的文件对象?
- android - Xamarin.Forms Android 应用程序在使用共享意图后启动 2 个进程
- mysql - Nodejs Web应用程序无法将用户序列化到会话中
- javascript - 带有axios回调的'for'内部的onload有错误
- ruby-on-rails - 如何为 ActiveRecordModel 的所有 where 查询添加条件?
- java - 如何使用正则表达式删除破折号和空格?
- mysql - 如果没有找到,Mysql max 函数返回一个空行。但是,在这种情况下,我需要它不返回任何行
- textarea - textarea的断行默认值
- reactjs - 在单次 useFetch 自定义挂钩中放置和发布请求
- angular - PCM 音频数据转换为 MP3 并流式传输每秒都有打嗝