【问题标题】:R Web Scraping: Error handling when web page doesn't contain a tableR Web Scraping:网页不包含表格时的错误处理
【发布时间】:2019-01-05 03:44:57
【问题描述】:

我在抓取网页时遇到了一些困难。具体来说,我正在抓取通常嵌入表格的网页。但是,对于没有嵌入表的实例,我似乎无法以不破坏循环的方式处理错误。

示例代码如下:

event = c("UFC 226: Miocic vs. Cormier", "ONE Championship 76: Battle for the Heavens", "Rizin FF 12")
eventLinks = c("https://www.bestfightodds.com/events/ufc-226-miocic-vs-cormier-1447", "https://www.bestfightodds.com/events/one-championship-76-battle-for-the-heavens-1532", "https://www.bestfightodds.com/events/rizin-ff-12-1538")
testLinks = data.frame(event, eventLinks)

for (i in 1:length(testLinks)) {
  print(testLinks$event[i])
  event = tryCatch(as.data.frame(read_html(testLinks$eventLink[i]) %>% html_table(fill=T)),
                   error = function(e) {NA})
}

第二个链接没有嵌入表格。我以为我会用我的 tryCatch 跳过它,但链接没有跳过它,而是打破了循环。

我希望找出一种方法来跳过没有表格的链接,但继续抓取列表中的下一个链接。要继续使用上面的示例,我希望 tryCatch 从第二个链接移动到第三个链接。

有什么帮助吗?非常感谢!

【问题讨论】:

    标签: r web-scraping try-catch rvest


    【解决方案1】:

    这里有一些问题需要解决。首先,您的链接被视为因素(您可以使用testLinks %>% sapply(class) 看到这一点,因此您需要使用as.chracter() 将它们转换为字符,我已经在下面的代码中完成了这一点。

    其次,您需要将每个scrape分配给一个列表元素,因此我们在events <- list()的循环外部创建一个列表,然后将每个scrape分配给列表的一个元素在循环内部,即events[[i]] <- "something" 没有列表,您只需用第二个覆盖第一个抓取,用第三个覆盖第二个抓取,依此类推。

    现在,当 url 不包含表格时,您的 tryCatch 将工作并分配 NA(不会出现错误)

    events <- list()
    for (i in 1:nrow(testLinks)) {
      print(testLinks$event[i])
      events[[i]] = tryCatch(as.data.frame(read_html(testLinks$eventLink[i] %>% as.character(.)) %>% html_table(fill=T)),
                       error = function(e) {NA})
    }
    
    events
    

    【讨论】:

    • 谢谢!当我从更广泛的程序中提取/修改示例代码时,我不小心引入了您发现的一些问题,但这非常有帮助 - 非常感谢!
    猜你喜欢
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2019-06-23
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多