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

问题描述 投票:0回答:1

我正在循环遍历一个充满网址的.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时循环,在某些时候我的循环在一些url上打破并且我得到以下错误:

> HTTP status was '500 Internal Server Error'

我想了解这个错误,以便我在URL函数中添加这个案例,以便在此url类型再次出现时忽略。

有什么想法吗 ?谢谢 !

r http web-scraping http-status-codes
1个回答
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)
}
© www.soinside.com 2019 - 2024. All rights reserved.