【问题标题】:Loop through error when checking http status code检查http状态码时循环错误
【发布时间】:2022-01-26 00:31:38
【问题描述】:

我有一个网站列表,我的目标是检查每个网站的状态代码。我有以下内容,其中urls 是网站列表。

for (i in seq_along(urls)) {
  r <- GET(test[i])
  s <- status_code(r)
}

当我运行 for 循环时,我收到以下消息: Error in curl::curl_fetch_memory(url, handle = handle) : schannel: SNI or certificate check failed: SEC_E_WRONG_PRINCIPAL (0x80090322) - The target principal name is incorrect.

我正在考虑使用 tryCatch 处理这个问题,但我不确定语法或是否将整个 for 循环放在 tryCatch 中。

【问题讨论】:

    标签: r dataframe for-loop error-handling http-status-codes


    【解决方案1】:

    for 循环实际上工作正常。

    # install.packages('httr')
    library(httr)
    
    urls <- c('https://stackoverflow.com/questions/70857408/loop-through-error-when-checking-http-status-code',
              'https://stackoverflow.com/')
    
    s <- numeric(length(urls))
    for (i in seq_along(urls)) {
      
      # if URLs are listed
      if(inherits(urls, 'list')) {
        r <- GET(urls[[i]])
      }
      # if URLs are concatenated
      if(inherits(urls, 'character')) {
        r <- GET(urls[i])
      }
      
      s[i] <- status_code(r)
    }
    
    #> s
    #[1] 200 200
    

    (在 OP 评论后编辑) 如果您想 try 某个 GET 是否有效,如果无效,则忽略错误并继续循环,您可以使用以下构造。

    s <- numeric(length(urls))
    for (i in seq_along(urls)) {
    
      # if URLs are listed
      if(inherits(urls, 'list')) {
        r <- try(GET(urls[[i]]))
        if(inherits(r, "try-error")) next
      }
    
      # if URLs are concatenated
      if(inherits(urls, 'character')) {
        r <- try(GET(urls[i]))
        if(inherits(r, "try-error")) next
      }
      
      s[i] <- status_code(r)
    }
    
    #> s
    #[1] 200 200
    

    【讨论】:

    • 感谢您的回复。我仍然收到消息:Error in curl::curl_fetch_memory(url, handle = handle) :schannel: SNI or certificate check failed: SEC_E_WRONG_PRINCIPAL (0x80090322) - The target principal name is incorrect.。在您链接的代码中,它似乎在第一个站点之后中止,将 s 的值设为 [1] 404 0 0 0 0 0 0 0 0 0 有没有办法在第一个站点之后忽略错误并继续循环遍历列表?
    • 我已经编辑了答案,如果迭代 i 失败,则还包括继续下一次迭代 i + 1 的选项。
    • 非常感谢!您的编辑帮助循环了错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2014-10-13
    • 1970-01-01
    相关资源
    最近更新 更多