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

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]“示例域”

但是,当我首先保存xml_document doc对象并再次加载它时,似乎所有内容都已清除.

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

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

我明白了:错误:没有匹配

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

还有一种情况是,当我运行文档时,在加载它之后,我收到一条消息,表明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,"/example.RData"))
doc %>% read_html %>% html_node("h1") %>% html_text

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念