R:rvest提取innerHTML

问题描述 投票:8回答:1

使用R中的rvest来抓取一个网页,我想从节点中提取相当于innerHTML的内容,特别是在应用html_text之前将换行符更改为换行符。

所需功能的示例:

library(rvest)
doc <- read_html('<html><p class="pp">First Line<br />Second Line</p>')
innerHTML(doc, ".pp")

应产生以下输出:

[1] "<p class=\"pp\">First Line<br>Second Line</p>"

有了rvest 0.2,这可以通过toString.XMLNode实现

# run under rvest 0.2
library(XML)
html('<html><p class="pp">First Line<br />Second Line</p>') %>% 
  html_node(".pp") %>% 
  toString.XMLNode
[1] "<p class=\"pp\">First Line<br>Second Line</p>"

随着更新的rvest 0.2.0.900,这不再适用。

# run under rvest 0.2.0.900
library(XML)
html_node(doc,".pp") %>% 
  toString.XMLNode
[1] "{xml_node}\n<p>\n[1] <br/>"

所需的功能通常在包write_xmlxml2函数中可用,rvest现在依赖于该函数 - 如果只有write_xml可以将其输出提供给变量而不是坚持写入文件。 (也不接受textConnection)。

作为一种解决方法,我可以暂时写入文件:

# extract innerHTML, workaround: write/read to/from temp file
html_innerHTML <- function(x, css, xpath) {
  file <- tempfile()
  html_node(x,css) %>% write_xml(file)
  txt <- readLines(file, warn=FALSE)
  unlink(file)
  txt
}
html_innerHTML(doc, ".pp") 
[1] "<p class=\"pp\">First Line<br>Second Line</p>"

然后,我可以将换行标记转换为换行符:

html_innerHTML(doc, ".pp") %>% 
  gsub("<br\\s*/?\\s*>","\n", .) %>%
  read_html %>%
  html_text
[1] "First Line\nSecond Line"

有没有更好的方法来实现这一点与现有的功能,例如, rvestxml2XML或其他套餐?特别是我想避免写入硬盘。

r web-scraping innerhtml tostring rvest
1个回答
0
投票

正如@ r2evans所指出的那样,as.character(doc)就是解决方案。

关于你最后的代码片段,它想要在将<br>转换为换行符时从节点中提取<br>分隔的文本,在当前未解析的rvest issue #175, comment #2中有一个解决方法:

此问题的简化版本:

doc <- read_html('<html><p class="pp">First Line<br />Second Line</p>')

# r2evan's solution:
as.character(rvest::html_node(doc, xpath="//p"))
##[1] "<p class=\"pp\">First Line<br>Second Line</p>"

# rentrop@github's solution, simplified:
innerHTML <- function(x, trim = FALSE, collapse = "\n"){
    paste(xml2::xml_find_all(x, ".//text()"), collapse = collapse)
}
innerHTML(doc)
## [1] "First Line\nSecond Line"
© www.soinside.com 2019 - 2024. All rights reserved.