【发布时间】:2018-05-31 12:54:28
【问题描述】:
我有大量指向我想在 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)
}
关于如何解决这个问题的任何建议?
非常感谢!
【问题讨论】:
标签: r web-scraping download