)
" />
本文介绍在 R 语言中利用 rvest 包结合 XPath 表达式,精准提取网页中不包含 标签的 段落,避免 CSS 选择器局限性,提升结构化文本抓取的准确性。
本文介绍在 r 语言中利用 rvest 包结合 xpath 表达式,精准提取网页中不包含 `` 标签的 ` ` 段落,避免 css 选择器局限性,提升结构化文本抓取的准确性。 在网页爬虫实践中,常需提取“纯文本段落”——即内容干净、不含嵌入链接()的 元素。但初学者易误用 CSS 伪类(如 :not(a)),该写法在 rvest 中不适用:CSS 选择器 :not(a) 表示“非 标签的元素”,而非“不包含 的 标签”,逻辑完全错误,导致结果错乱或为空。 正确解法是使用 XPath 表达式,其支持嵌套关系判断。关键语法为: ; (包括直接子链接和深层嵌套链接)。 完整可运行示例: ⚠️ 注意事项: 位于 article > div 下,若结构变化需调整 //article/div/p 部分); 总结:当筛选依赖父子/后代关系的 HTML 元素时,XPath 是 rvest 中不可替代的利器。掌握 descendant::、child::、not() 等基础谓词,能显著提升复杂选择场景下的鲁棒性与可维护性。//article/div/p[not(descendant::a)]
library(rvest)
url <- "https://www.news4teachers.de/2023/08/schaemt-euch-deutschland-steht-vor-den-vereinten-nationen-am-pranger-weil-es-die-inklusion-an-schulen-verweigert/"
html <- read_html(url)
# ✅ 正确:XPath 精准匹配不含 <a> 的 <p>
clean_paragraphs <- html |>
html_elements(xpath = "//article/div/p[not(descendant::a)]")
# 提取纯文本(自动去除 script/iframe 等干扰内容)
text_content <- clean_paragraphs |>
html_text(trim = TRUE) |>
\(x) x[nzchar(x)] # 过滤空字符串
print(text_content[1:3])
# [1] "GENF. \"Schämt Euch!\" – so heißt es auf einem Transparent, das..."
# [2] "Es ist fast schon dreist, wie Deutschland auf die offizielle Staatenp..."
# [3] "Auch in einer gemeinsamen Stellungnahme von einem Bündnis deutscher N..."

















