创建函数以避免R for循环中的url错误

时间:2018-09-17 15:35:23

标签: r http web-scraping http-status-codes

我正在遍历一个填充了URL的.csv,以抓取网站(授权抓取)。

我正在使用trycatch函数来尝试避免for循环中的中断。 但是我注意到某些网址停止了(使用download.file)。

所以我现在正在使用«,这是有效的网址吗? »函数摘自这篇文章: [Scrape with a loop and avoid 404 error

url_works <- function(url){
tryCatch(
    identical(status_code(HEAD(url)),200L), 
    error = function(e){
        FALSE
    })
}

但是即使使用了此函数,并且仅在函数的结果为TRUE时才循环,但有时我的循环会在某些网址上中断,并且会出现以下错误:

> HTTP status was '500 Internal Server Error'

我想了解这个错误,因此我将这种情况添加到URL函数中,以便在再次出现此url类型的情况下可以忽略。

有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

您的tryCatch语法错误,我还更改了错误消息以显示错误:

通用tryCatch如下:

tryCatch({
    operation-you-want-to-try
   }, error = function(e) do-this-on-error
)

对于您的代码:

url_works <- function(url){
    tryCatch({
        s1 <- status_code(HEAD(url))
        }, error = function(e) print(paste0(url, " ", as.character(e)))
    )
    identical(s1, 200L)
}