【发布时间】:2018-12-17 21:01:41
【问题描述】:
此代码尝试下载不存在的页面:
url <- "https://en.wikipedia.org/asdfasdfasdf"
status_code <- download.file(url, destfile = "output.html", method = "libcurl")
这会返回 404 错误:
trying URL 'https://en.wikipedia.org/asdfasdfasdf'
Error in download.file(url, destfile = "output.html", method = "libcurl") :
cannot open URL 'https://en.wikipedia.org/asdfasdfasdf'
In addition: Warning message:
In download.file(url, destfile = "output.html", method = "libcurl") :
cannot open URL 'https://en.wikipedia.org/asdfasdfasdf': HTTP status was '404 Not Found'
但code 变量仍然包含 0,尽管download.file 的文档指出返回值是:
一个(不可见的)整数代码,0 表示成功,非零表示失败。对于“wget”和“curl”方法,这是外部程序返回的状态码。 “内部”方法可以返回 1,但在大多数情况下会抛出错误。
如果我使用curl或wget作为下载方法,结果是一样的。我在这里想念什么?是调用warnings() 并解析输出的唯一选择吗?
我已经看到 other questions 关于使用 download.file,但没有一个(我能找到)实际检索 HTTP 状态代码。
【问题讨论】:
-
我不知道 R,也不知道 download.file 包装器,但是获取代码的底层 libcurl 方法是
long response_code; curl_easy_getinfo(ch,CURLINFO_RESPONSE_CODE,&response_code);- 检查您的 download.file api 是否以某种方式暴露了 libcurl 的 curl_easy_getinfo()