我尝试缓存 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_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
。
关于r - 缓存read_html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51950167/