代码之家  ›  专栏  ›  技术社区  ›  Felipe Alvarenga

如何使用httr GET命令刷新或重试特定网页?

  •  7
  • Felipe Alvarenga  · 技术社区  · 8 年前

    我需要使用不同的“键”访问同一网页,以获取它提供的特定内容。

    我有钥匙清单 x 我使用 GET 命令来自 httr 包访问网页,然后检索我需要的信息 y .

    library(httr)
    library(stringr)
    library(XML)
    
    for (i in 1:20){
        h1 = GET ( paste0("http:....categories=&query=", x[i]),timeout(10))
        par = htmlParse(file = h1)
    
        y[i]=xpathSApply(doc = par, path = "//h3/a" , fun=xmlValue)
    
    }
    

    问题是经常会超时,这会中断循环。

    因此,如果超时,我想刷新网页或重试GET命令,因为我怀疑问题出在我试图访问的网站的互联网连接上。

    我的代码的工作方式是超时中断循环。我需要忽略错误并进入下一次迭代,或者重试访问网站。

    3 回复  |  直到 6 年前
        1
  •  12
  •   hrbrmstr    8 年前

    看看 purrr::safely() 。您可以包装 GET 像这样的:

    safe_GET <- purrr::safely(GET)
    

    这消除了 tryCatch() 让您做到:

    resp <- safe_GET("http://example.com") # you can use all legal `GET` params
    

    你可以测试 resp$result 对于 NULL 。把它放到你的重试循环中,你就可以开始了。

    通过执行以下操作,您可以看到这一点:

    str(safe_GET("https://httpbin.org/delay/3", timeout(1)))
    

    这将要求httpbin服务在响应前等待3秒,但在 得到 请求为1s。我把它包起来了 str() 显示结果:

    List of 2
     $ result: NULL
     $ error :List of 2
      ..$ message: chr "Timeout was reached"
      ..$ call   : language curl::curl_fetch_memory(url, handle = handle)
      ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
    

    所以,如果需要的话,你甚至可以查看消息。

        2
  •  5
  •   François M.    8 年前

    http_status(h1) 可以帮助您了解问题所在:

    a <- http_status(GET("http://google.com"))
    a
    
    $category
    [1] "Success"
    
    $reason
    [1] "OK"
    
    $message
    [1] "Success: (200) OK"
    

    b <- http_status(GET("http://google.com/blablablablaba"))
    b
    
    $category
    [1] "Client error"
    
    $reason
    [1] "Not Found"
    
    $message
    [1] "Client error: (404) Not Found"
    

    看看这个 list of HTTP status codes 知道你得到的代码意味着什么。

    此外 tryCatch 可以帮助您实现您想要的:

    tryCatch({GET(h1)}, error = function(e){print("error")})
    
        3
  •  1
  •   amrrs    4 年前

    一个新的 httr 作用 RETRY() 在这些情况下也很方便。 重试() 让您尝试呼叫,直到成功。

    httr::RETRY("GET", "http://httpbin.org/status/200")
    

    文档- https://httr.r-lib.org/reference/RETRY.html