【问题标题】:Cache read_html缓存 read_html
【发布时间】:2019-01-27 17:31:00
【问题描述】:

我尝试缓存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 时也会出现同样的问题。

【问题讨论】:

    标签: r caching web-scraping memoise


    【解决方案1】:

    您始终可以使用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

    【讨论】:

    • 感谢您的想法,但我放弃了它并缓存了派生数量。 as_list(html) 非常慢(维基页面需要 1 分钟),之后我只能找到部分属性 - 看起来翻译有一些损失。
    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2020-02-01
    • 1970-01-01
    • 2022-11-25
    • 2019-08-17
    • 2017-05-14
    • 2020-01-22
    • 2017-12-30
    相关资源
    最近更新 更多