我有大量 pdf 文件的链接,我想在 for 循环中使用 download.file 下载这些文件。我的解决方案工作正常,但在遇到错误时停止(许多文件不起作用)。我想在 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)
}
关于如何解决这个问题有什么建议吗?
非常感谢!
Put download.file
inside 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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)