R {xml_node} 到纯文本,同时保留标签?

R {xml_node} to plain text while preserving the tags?

我想完全按照 xml2::xml_text()rvest::html_text() 做,但保留标签而不是替换,例如<br>\n。 objective 例如抓取网页,提取我想要的节点,然后将普通 HTML 存储在变量中,就像 write_html() 将其存储在文件中一样。

我该怎么做?

具有讽刺意味的是,事实证明 as.character() 工作得很好。

因此:

library(rvest)
html <- read_html("http://whosebug.com")

res <– html %>%
         html_node("h1") %>%
         as.character()

> res

[1] "<h1 class=\"-title\">Learn, Share, Build</h1>"

这是我当前用例中所需的输出。

另一方面,为了比较是否需要剥离标签:

res <- html %>%
         html_node("h1") %>%
         html_text()

> res
[1] "Learn, Share, Build"