无法保存 - 在 R 中加载从 rvest 生成的 xml_document

Cannot save - load xml_document generated from rvest in R

read_html 函数生成一个 xml_document,我想保存它,稍后加载它以解析它。

问题是加载 xml_document 后里面没有 html。

library(rvest)
library(magrittr)
doc <- read_html("http://www.example.com/")
doc %>% html_node("h1") %>% html_text

我得到:[1] "Example Domain"

但是当我先保存 xml_document doc 对象并再次加载它时,似乎一切都已清除。

save(doc, file=paste0(getwd(), "/example.RData"))
rm(doc)

load(file=paste0(getwd(), "/example.RData"))
doc %>% html_node("h1") %>% html_text

我得到:Error: No matches

或者当我 运行 doc 我得到: {xml_document} 一个空 xml_document.

当我 运行 doc 加载它后,我收到一条消息说 RStudio 已停止工作。

我在两台不同的 windows 机器上试过,遇到了同样的问题。

sessionInfo()

R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] magrittr_1.5     rvest_0.3.1.9000 xml2_0.1.2      

loaded via a namespace (and not attached):
[1] httr_1.1.0  R6_2.1.2    tools_3.3.0 Rcpp_0.12.5

我找到了一个解决方法,虽然效率不高,但可以完成工作。

逻辑是将xml_document保存为字符串,然后用read_html再次读入。

library(rvest)
library(magrittr)
doc <- read_html("http://www.example.com/")

# convert it to character
doc %<>% as("character")

save(doc, file=paste0(getwd(), "/example.RData"))
rm(doc)

load(file=paste0(getwd(), "/example.RData"))
doc %>% read_html %>% html_node("h1") %>% html_text

我写了一些临时 函数来完成这个任务。它们比之前的答案稍微好一些,因为它们适用于 rvest 对象的列表,并且它们使用 RDS 而不是 RData 文件。这允许人们随意命名对象。

write_rvest = function(x, path, ...) {
  #convert to character
  #is list?
  if (is.list(x)) {
    x %<>% map(as.character)
  } else {
    x %<>% as.character
  }

  #save
  write_rds(x, path = path, ...)
}

read_rvest = function(path) {
  #load from file
  x = read_rds(path)

  #read
  if (is.list(x)) {
    x %<>% map(read_html)
  } else {
    x %<>% read_html
  }

  x
}

平等测试有效,但身份测试失败。尽管如此,这些对象仍然有效,并且它们的字节大小相同,所以我不知道为什么身份会失败。可能对内存位置敏感。

此处与基本 R 代码中的 Delete 相同的包装函数。

library(rvest)

write_rvest = function(x, file, ...) {
  #convert to character
  #is list?
  if (is.list(x)) {
    x = Map(as.character, x)
  } else {
    x = as.character(x)
  }

  #save
  saveRDS(x, file = file, ...)
}

read_rvest = function(file) {
  #load from file
  x = readRDS(file)

  #read
  if (is.list(x)) {
    x <- Map(read_html, x)
  } else {
    x <- read_html(x)
  }

  x
}