【问题标题】:How to check If file exists in the url before use download.file in R在R中使用download.file之前如何检查url中是否存在文件
【发布时间】:2020-02-20 11:28:37
【问题描述】:

我有一个问题,我不知道如何解决它。 我有一个直接下载一些文件的 url 列表。

例如。

x<-list("https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_200219.csv",
"http://sdw.ecb.europa.eu/quickviewexport.do?SERIES_KEY=120.EXR.M.USD.EUR.SP00.A&type=csv")

name_file<-list("name_1.csv","name_2.csv")

在这种情况下,下面的脚本可以正常工作,但如果一个或多个 url 不起作用,tryCatch 不会向我返回消息。请有人可以帮助我并告诉我我的错误在哪里?

  for(i in seq_along(x)) {
  x<-as.character(x[i])
  nse.folder = paste0("directory_files/",name_file[i])
  tryCatch({download.file(x, destfile = nse.folder, method='curl')}, error = function(e) "Error: this url doesn't work!")
  Sys.sleep(4)
  }

测试我剪切的脚本,比如url,像这样:

x<-list("https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/",
"http://sdw.ecb.europa.eu/quickviewexport.do?")

我应该在哪里改进代码?

提前谢谢你

【问题讨论】:

    标签: r try-catch rcurl


    【解决方案1】:

    您可以使用HEAD 请求。在 R 中,它在包 httr 中可用。可以在Wikipedia 上找到返回代码。这个SO post 可能有用。

    一个非常简单的函数可以是

    urlFileExist <- function(url){
      HTTP_STATUS_OK <- 200
      hd <- httr::HEAD(url)
      status <- hd$all_headers[[1]]$status
      list(exists = status == HTTP_STATUS_OK, status = status)
    }
    
    lapply(x, urlFileExist)
    #[[1]]
    #[[1]]$exists
    #[1] TRUE
    #
    #[[1]]$status
    #[1] 200
    #
    #
    #[[2]]
    #[[2]]$exists
    #[1] TRUE
    #
    #[[2]]$status
    #[1] 200
    

    【讨论】:

    • 非常感谢您的回答。非常有帮助,但最后我使用了函数 try.我做了什么?我使用了这个解决方案:try(download.file(x, destfile = nse.folder, method='curl', quiet =TRUE))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2019-03-25
    • 2021-05-31
    • 2015-02-21
    • 1970-01-01
    • 2022-08-09
    • 2016-02-10
    相关资源
    最近更新 更多