从URL下载文件是网络编程中的一个基本任务。在R语言中,可以使用多种方法来实现这一功能,包括download.file
函数、read.csv
函数的file
参数、httr
包中的GET
函数等。
download.file
函数。downloader
包或其他并行计算方法。httr
包中的GET
函数。以下是一个使用download.file
函数从多个URL下载CSV文件的示例:
urls <- c(
"http://example.com/file1.csv",
"http://example.com/file2.csv",
"http://example.com/file3.csv"
)
for (url in urls) {
filename <- paste0("downloaded_file_", gsub("[^[:alnum:]]", "_", basename(url)))
download.file(url, destfile = filename, method = "auto")
cat("Downloaded", filename, "\n")
}
tryCatch
捕获错误并进行处理。for (url in urls) {
filename <- paste0("downloaded_file_", gsub("[^[:alnum:]]", "_", basename(url)))
for (i in 1:3) {
tryCatch({
download.file(url, destfile = filename, method = "auto")
cat("Downloaded", filename, "\n")
break
}, error = function(e) {
if (i == 3) {
cat("Failed to download", url, "\n")
} else {
cat("Retrying to download", url, "\n")
}
})
}
}
httr
包中的GET
函数,并添加身份验证信息。library(httr)
for (url in urls) {
filename <- paste0("downloaded_file_", gsub("[^[:alnum:]]", "_", basename(url)))
response <- GET(url, authenticate("username", "password"))
if (http_status(response)$category == "Success") {
writeBin(content(response, "raw"), filename)
cat("Downloaded", filename, "\n")
} else {
cat("Failed to download", url, "\n")
}
}
通过以上方法,你可以从多个URL下载CSV文件,并处理可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云