R、rvest、文本抓取 - 根据标签从 HTML 节点删除特定元素

R, rvest, text scraping - drop specific elements from a HTML node, based on their tags

这是一个快速模拟代码

<div class = "speech">

<p>
<a id = "xxxx"> </a>
<b> <a href = "xxxx"> xxxx </a> </b>
Text text text <i> text </i> text
<br>
text text <sup> text </sup> text
</p>

<p>
<a id = "xxxx"> </a>
<b> <a href = "xxxx"> xxxx </a> </b>
Text text text <i> text </i> text
<br>
text text <sup> text </sup> text
</p>

</div>

我想获得一个列表或数据框,其中每个“p”节点的文本内容连接起来作为此 list/data 框架的唯一条目。 所以,基本上,我想从结果中删除“a”和“b”子节点,同时每个“p”标签的文本内容构成 list/data 框架中的一个字符串条目,没有“i”、“br”和“sup”标签(但仍然是这些标签内的文本。

非常感谢!

这是我的代码:

GET(url = "https://xxx") %>%
  read_html() %>%
  html_nodes(xpath = "//div[@class = 'speech']//text()") %>%
  as.character()

我被困在这里了。得到的是一个列表,有文本元素,但是:

foo.html 成为包含您的示例的文件 html:

library(tidyverse)
library(rvest)
library(xml2)

doc <-
  read_html("foo.html") %>%
  html_nodes(xpath = "//p") %>%
  as_xml_document(root = ".")

xml_remove(
  doc %>% xml_find_all(xpath = "//a|b")
)

doc %>%
  as_list() %>%
  pluck(".") %>%
  map(~ .x %>% purrr::simplify() %>% paste0(collapse = " "))

输出:

$p
[1] "\n \n list(\" \", \" \") \nText text text  list(\" text \")  text\n list() \ntext text  list(\" text \")  text\n"

$p
[1] "\n \n list(\" \", \" \") \nText text text  list(\" text \")  text\n list() \ntext text  list(\" text \")  text\n"