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

dim*_*_ps 8 xml r rvest

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

问题是加载xml_document后,其中没有html.

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

我明白了: [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
Run Code Online (Sandbox Code Playgroud)

我明白了: 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
Run Code Online (Sandbox Code Playgroud)

dim*_*_ps 4

我找到了一种解决方法,效率不是很高,但它可以完成工作。

逻辑是将 保存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
Run Code Online (Sandbox Code Playgroud)