代码之家  ›  专栏  ›  技术社区  ›  Dieter Menne

缓存读取HTML

  •  1
  • Dieter Menne  · 技术社区  · 8 年前

    我试图缓存 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
    

    这会失败,因为只有外部指针存储在重新运行时不再有效的文件中。当我使用 memoise 在 read_html .

    1 回复  |  直到 8 年前
        1
  •  1
  •   d125q    8 年前

    你可以一直使用 as_list 和 as_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_xml 和 write_xml .