【问题标题】:Try and catch in r while scraping在刮擦时尝试在 r 中捕获
【发布时间】:2017-11-05 06:24:45
【问题描述】:

我有包含 ID 号的数据表(npi1_list),根据我从网站上进行网络抓取的数字,npi 列表将匹配网站中的 ID 号并为我提取记录。

library("rvest")
library("data.table")    
final<- NULL
    for(i in 8000:200000){
    url<-paste("http://www.npinumberlookup.org/getResultDetails.php?
    npinum=",npi1_list[i,1],sep='')
    webpage<-read_html(url)
    Name<- html_nodes(webpage, 'table:nth-child(8) tr:nth-child(1) td~ td+ td ,
    table:nth-child(6) tr:nth-child(1) td~ td+ td')
    rank_data <-html_text(Name)
    final <- rbind(final,rank_data)
    print(i)
    Sys.sleep(1)
    }   

这工作正常,但有时会显示错误连接超时 80 端口错误,然后我必须从循环终止的位置初始化 i 并重新运行 for 循环。如何在上面实现 try 和 catch 选项for 循环,这样我就可以自动化直到第 200000 行。

【问题讨论】:

  • 您为什么不直接使用downloadable full database 和/或每周更新?锤击一个网站——他们明确声明至少20s crawl-delay——对于你可以在其他地方大量找到的数据来说并不酷。它们也不是权威来源,所以我也会担心数据完整性问题。

标签: r try-catch


【解决方案1】:
library("rvest")
library("data.table")    
final<- NULL
for(i in 8000:200000){        
    repeat{
        successful = T   
        tryCatch({
            url<-paste("http://www.npinumberlookup.org/getResultDetails.php?
            npinum=",npi1_list[i,1],sep='')
            webpage<-read_html(url)
            Name<- html_nodes(webpage, 'table:nth-child(8) tr:nth-child(1) td~ td+ td ,
            table:nth-child(6) tr:nth-child(1) td~ td+ td')
            rank_data <-html_text(Name)
            final <- rbind(final,rank_data)
            print(i)
        }, error = function(e){
            print(e)
            print(paste0('connection error on ', i))
            successful <<- F
        }) 
        Sys.sleep(1)
        if(successful)
            break
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多