r - 缓存read_html

标签 r caching web-scraping memoise

我尝试缓存 read_html/xml2 以避免开发过程中服务器泛滥

library(digest)
library(xml2)
url = "https://en.wikipedia.org"
cache = digest(url)
if (file.exists(cache)) {
  cat("Reading from cache\n")
  html = readRDS(cache)
} else {
  #Sys.sleep(3)
  cat("Reading from web\n")
  html = xml2::read_html(url) 
  saveRDS(html, file = cache)
}
html

这会失败,因为文件中仅存储外部指针,这些指针在重新运行时不再有效。当我在 read_html 上使用 memoise 时,也会出现同样的问题。

最佳答案

您始终可以使用 as_listas_xml_document 来回转换。

library(digest)
library(xml2)
url = "https://en.wikipedia.org"
cache = digest(url)
if (file.exists(cache)) {
  cat("Reading from cache\n")
  html = as_xml_document(readRDS(cache))
} else {
  cat("Reading from web\n")
  html = read_html(url) 
  saveRDS(as_list(html), file = cache)
}
html

或者,查看 read_xmlwrite_xml

关于r - 缓存read_html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51950167/

相关文章:

sorting - 根据 2D/3D 点的相互距离对数组进行启发式排序

asp.net - ASP.net HttpRuntime.Cache 使用的默认序列化是什么

python - Beautifulsoup + Python HTML UL 定位、创建列表并附加到变量

python - 如何从 Facebook 页面的 xhr 响应中获取有用的数据?

r - 如何根据R中坐标之间的距离将数据点分组在一起?

r - R中lm模型中 'I'关键字的意义

java - 通过 setter 或服务使缓存失效?

r - 在 Wiki 的网球 table 上使用 Rvest 进行网页抓取

r - 在 R 中使用 "sink()"将写入从文件切换到标准输出

r - 如何计算数据集中 NA 值的数量?