如何确定url对象是否返回' 404 Not Found'?

时间:2014-04-17 17:11:22

标签: r url http-status-code-404

简单地说:if

x <- read.csv(url)

存在,然后R将返回该URL的内容。一个很好的例子,如果你想尝试一下,可能是&#34; http://ichart.finance.yahoo.com/table.csv?s=IBM&a=00&b=1&c=2008&d=03&e=4&f=2014&g=d&ignore=.csv&#34; 。如果将该特定URL分配给url并按上述方式运行,则会将包含过去5年IBM股票数据的Yahoo网站中的data.frame加载到x中。

但是如何预先告知,如果任何给定的网址会让你获得404&#39;

类似的东西:

is.404.or.not(url)

或者

status(connect.to(url))

谢谢!

1 个答案:

答案 0 :(得分:7)

您可以使用RCurl包:

R> library(RCurl)
Loading required package: bitops
R> url.exists("http://google.com")
[1] TRUE
R> url.exists("http://csgillespie.org")
[1] FALSE

或者,您可以使用httr

R> library(httr)
R> http_status(GET("http://google.com"))
$category
[1] "success"

$message
[1] "success: (200) OK"

R> http_status(GET("http://csgillespie.org"))
$category
[1] "server error"

$message
[1] "server error: (503) Service Unavailable"