gpt4 book ai didi

r - 在 R 中使用 download.file 下载时跳过错误文件

转载 作者:行者123 更新时间:2023-12-04 01:56:06 25 4
gpt4 key购买 nike

我有大量指向 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)

}

有关如何解决此问题的任何建议?

非常感谢!

最佳答案

download.filetryCatch .例如

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"

关于r - 在 R 中使用 download.file 下载时跳过错误文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50624864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com