【问题标题】:I would like to check if url redirects to another page in R我想检查 url 是否重定向到 R 中的另一个页面
【发布时间】:2014-03-07 23:41:27
【问题描述】:

我需要检查 url 是否重定向到 R 中的另一个页面。有可能吗?

【问题讨论】:

  • 我试过 Get() 但它很慢..还有其他选择吗?谢谢

标签: r http url


【解决方案1】:

查看httr 包,还有GET 函数:

> library(httr)
> names(GET("http://www.stackoverflow.com"))
[1] "url"         "handle"      "status_code" "headers"     "cookies"
[6] "content"     "times"       "config"     
> GET("http://www.stackoverflow.com")$status_code
[1] 200

【讨论】:

  • HEAD() 会更高效,因为您不关心内容。
  • @hadley:对于相同的 URL,特定服务器返回 404 和 HEAD 和 200 和 GET。这是常见的,还是只是配置异常糟糕的服务器?
  • 服务器配置错误
  • 对于成功重定向的页面返回 200,而不是 300。例如,httr::HEAD("https://ucalgary.ca") 返回 statuscode = 200,但使用 url https://www.ucalgary.caHEAD(xxx)$times 的第一个元素命名为redirect 等。
【解决方案2】:

按照建议使用HEAD,但检查返回对象的url和你输入的url是否相同

url <- "https://google.ca/"
stat <- httr::HEAD(url)
stat
Response [https://www.google.ca/]
  Date: 2018-02-17 13:57
  Status: 200
  Content-Type: text/html; charset=ISO-8859-1
<EMPTY BODY>
stat$times
     redirect    namelookup       connect   pretransfer starttransfer         total 
     0.054985      0.000030      0.000033      0.000109      0.082320      0.137389 

times 的第一个元素是redirect。我不能总是确定重定向页面看起来像这样,所以我只需检查 urlHEAD(url)$url 是否相同:

HEAD(url)$url == url
[1] FALSE # FALSE for redirect

请注意,在您的网址末尾添加 / 的页面也被视为重定向:

HEAD("https://www.google.ca")$url == "https://www.google.ca"
[1] FALSE
HEAD("https://www.google.ca/")$url == "https://www.google.ca/"
[1] TRUE

因此,如果您关心诸如此类的小事是否被视为重定向,则可能需要处理返回的 url。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2017-09-11
    • 2023-02-02
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多