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

前端之家收集整理的这篇文章主要介绍了无法保存 – 从R中的rvest生成的xml_document前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
read_html函数生成一个xml_document,我想保存,稍后加载它来解析它.

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

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

我得到:[1]“示例域”

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

  1. save(doc,file=paste0(getwd(),"/example.RData"))
  2. rm(doc)
  3.  
  4. load(file=paste0(getwd(),"/example.RData"))
  5. doc %>% html_node("h1") %>% html_text

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

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

还有一种情况是,当我运行文档时,在加载它之后,我收到一条消息,表明RStudio已停止工作.

我在两台不同的Windows机器上试过它,遇到了同样的问题.

  1. sessionInfo()
  2.  
  3. R version 3.3.0 (2016-05-03)
  4. Platform: x86_64-w64-mingw32/x64 (64-bit)
  5. Running under: Windows 7 x64 (build 7601) Service Pack 1
  6.  
  7. locale:
  8. [1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252
  9. [3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
  10. [5] LC_TIME=English_United Kingdom.1252
  11.  
  12. attached base packages:
  13. [1] stats graphics grDevices utils datasets methods base
  14.  
  15. other attached packages:
  16. [1] magrittr_1.5 rvest_0.3.1.9000 xml2_0.1.2
  17.  
  18. loaded via a namespace (and not attached):
  19. [1] httr_1.1.0 R6_2.1.2 tools_3.3.0 Rcpp_0.12.5
我找到了一个解决方法,效率不高但是它完成了工作.

逻辑是将xml_document保存为字符串,并使用read_html再次读取它.

  1. library(rvest)
  2. library(magrittr)
  3. doc <- read_html("http://www.example.com/")
  4.  
  5. # convert it to character
  6. doc %<>% as("character")
  7.  
  8. save(doc,"/example.RData"))
  9. doc %>% read_html %>% html_node("h1") %>% html_text

猜你在找的XML相关文章