r - 使用 R 中的 download.file 下载时跳过错误文件
问题描述
我有大量指向我想在 for 循环中使用 download.file 下载的 pdf 文件的链接。我的解决方案工作正常,但遇到错误时会停止(许多文件不起作用)。我想在我的 download.file 函数中添加一个功能,告诉 R 如果下载产生错误则跳过文件并打印一条消息,其中包含遇到错误的页面名称。
我发现在这种情况下 tryCatch 可能是一个很好的解决方案,但我不完全确定在哪里放置它(我尝试了多种方法,但都没有奏效)。
这是我的代码:
for (i in length(files) {
# Reads the html links
html <- read_html(files[i])
reads_name <- html_nodes(html, 'h1')
name <- trimws(html_text(reads_name) )
# Extracts the pdf. link from all links that the webpage contains
webpagelinks <- html_attr(html_nodes(html, "a"), "href")
extract_pdf_link <- webpagelinks[grepl("\\pdf", webpagelinks)]
# downloads the pdf file from the pdf link, here is where I get the error
download.file(extract_pdf_link, destfile = paste0(name, "_paper.pdf") ,
mode = "wb")
skip_with_message = simpleError('Did not work out')
tryCatch(print(name), error = function(e) skip_with_message)
}
关于如何解决这个问题的任何建议?
非常感谢!
解决方案
放在download.file
里面tryCatch
。例如
files <- c("http://foo.com/bar.pdf", "http://www.orimi.com/pdf-test.pdf", "http://bar.com/foo.pdf")
oldw <- getOption("warn")
options(warn = -1)
for (file in files) {
tryCatch(download.file(file, tempfile(), mode = "wb", quiet = FALSE),
error = function(e) print(paste(file, 'did not work out')))
}
options(warn = oldw)
我在开始时关闭警告options(warn = -1)
以抑制无关的警告消息,并在最后恢复以前的设置。这会给你一个像
# trying URL 'http://foo.com/bar.pdf'
# [1] "http://foo.com/bar.pdf did not work out"
# trying URL 'http://www.orimi.com/pdf-test.pdf'
# Content type 'application/pdf' length 20597 bytes (20 KB)
# ==================================================
# downloaded 20 KB
# trying URL 'http://bar.com/foo.pdf'
# [1] "http://bar.com/foo.pdf did not work out"
推荐阅读
- spartacus-storefront - 如何根据 Spartacus 中的用户配置文件自动更改站点之间的货币
- c++ - 如何在c ++中使用kill函数杀死进程?
- typescript - 在 TypeScript 中按类型排除函数参数
- java - Android Studio 从 FireBase 存储异步下载文件
- javascript - 在javascript上使用javascript模拟点击事件:href
- firebase - nuxt.js 中出现意外的模板字符串表达式(no-template-curly-in-string)
- azure - 正确部署 AAD Pod 身份
- r - 在一个选项卡中创建 rmd 输出后,闪亮的仪表板主体显示为在所有选项卡中包含 rmd 输出
- mysql - 当我从 fetch 发布时,我的数据库将所有值记录为 0。Node.js mySql
- pandas - 返回使用 Pivot 函数的重复索引