检查http状态码时循环报错

Loop through error when checking http status code

我有一个网站列表,我的目标是检查每个网站的状态代码。我有以下内容,其中 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.

for 循环实际上工作正常。

# install.packages('httr')
library(httr)

urls <- c('
          'https://whosebug.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