R 网页抓取:网页不包含表格时的错误处理



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

下面的示例代码:

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从第二个链接移动到第三个链接。

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

这里有一些问题需要解决。首先,你的链接是考虑因素的(你可以在testLinks %>% sapply(class)中看到这一点,所以你需要使用as.chracter()将它们转换为字符

其次,您需要将每个刮片分配给一个列表元素,因此我们在带有events <- list()的循环的外部创建一个列表,然后将每个刮片分配给循环内的列表中的一个元素,即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

最新更新