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

wht*_*obj 7 url r http-status-code-404

简单地说:如果

x <- read.csv(url)
Run Code Online (Sandbox Code Playgroud)

存在,然后R将返回该URL的内容.一个很好的例子,如果你想尝试一下,可能是" 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 ".该特定URL如果被分配给url并按上述方式运行,则会将包含过去5年IBM股票数据的Yahoo网站的data.frame加载到x中.

但是,如何预先知道,如果任何给定的网址会让你404?

就像是:

is.404.or.not(url)
Run Code Online (Sandbox Code Playgroud)

或者可能

status(connect.to(url))
Run Code Online (Sandbox Code Playgroud)

谢谢!

csg*_*pie 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
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用该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"
Run Code Online (Sandbox Code Playgroud)