我想做什么xml2::xml_text()或rvest::html_text()做什么,但保留标签而不是<br>用\n. 目标是例如抓取网页,提取我想要的节点,并将纯 HTML 存储在变量中,就像write_html()将其存储在文件中一样。
我怎样才能做到这一点?
具有讽刺意味的是,事实证明这as.character()很好用。
所以:
library(rvest)
html <- read_html("http://stackoverflow.com")
res <– html %>%
html_node("h1") %>%
as.character()
> res
[1] "<h1 class=\"-title\">Learn, Share, Build</h1>"
Run Code Online (Sandbox Code Playgroud)
这是我当前用例中所需的输出。
另一方面,为了比较是否需要剥离标签:
res <- html %>%
html_node("h1") %>%
html_text()
> res
[1] "Learn, Share, Build"
Run Code Online (Sandbox Code Playgroud)