如何在rvest中进行网页抓取时跳过网页
我正在尝试使用R中的rvest包收集信息。 在使用for循环收集数据时,我发现一些页面不包含信息,因此出现了一个错误:error in open.connection(x,“rb”):HTTP error 404 这是我的R代码。页码15138和15140有信息,而15139没有。如何使用for循环函数跳过15139如何在rvest中进行网页抓取时跳过网页,r,web-scraping,rvest,R,Web Scraping,Rvest,我正在尝试使用R中的rvest包收集信息。 在使用for循环收集数据时,我发现一些页面不包含信息,因此出现了一个错误:error in open.connection(x,“rb”):HTTP error 404 这是我的R代码。页码15138和15140有信息,而15139没有。如何使用for循环函数跳过15139 library(rvest) library(dplyr) library(tidyr) library(stringr) library(stringi) source_u
library(rvest)
library(dplyr)
library(tidyr)
library(stringr)
library(stringi)
source_url <- "https://go2senkyo.com/local/senkyo/"
senkyo <- data.frame()
for (i in 15138:15140) {
Sys.sleep(0.5)
target_page <- paste0(source_url, i)
recall_html <- read_html(target_page, encoding = "UTF-8")
prefecture <- recall_html %>%
html_nodes(xpath='//*[contains(concat( " ", @class, " " ), concat( " ", "column_ttl_small", " " ))]') %>%
html_text()
city <- recall_html %>%
html_nodes(xpath='//*[contains(concat( " ", @class, " " ), concat( " ", "column_ttl", " " ))]') %>%
html_text()
city <- trimws(gsub("[\r\n]", "", city ))
senkyo2 <- cbind(prefecture, city)
senkyo <- rbind(senkyo , senkyo2)
}
库(rvest)
图书馆(dplyr)
图书馆(tidyr)
图书馆(stringr)
图书馆(stringi)
source\u url您可以通过几种不同的方式处理异常。我是一个noob
,但这里有一些适合你的选择
定制您的线圈范围
如果知道不需要值15139
,可以从选项向量中删除,如:
for (i in c(15138,15140)) {
这将在运行循环时完全忽略1539
添加控制流
这与裁剪循环范围基本相同,但处理循环本身内的异常,如:
for (i in 15138:15140) {
Sys.sleep(0.5)
# control statement
if (i == 15139 {
next # moves to next iteration of loop, in this case 15140
}
target_page <- paste0(source_url, i) # not run if i == 15139, since loop skipped to next iteration
我感谢你的有益评论。虽然我尝试了使用class(recall_html)==“try error”的第三种解决方案,但它出现了一个错误,如:In if(class(recall_html)==“try error”){:条件的长度大于1,只使用第一个元素。请告诉我如何处理此警告?哎呀,用try()替换tryCatch()
请告诉我此更新的解决方案是否满足您的需要,如果满足,请投票接受答案。谢谢!多亏您的帮助,我可以解决问题!非常感谢您。
# wrap the part of your code that can break in try()
recall_html <- try(read_html(target_page, encoding = "UTF-8"))
# you'll still see your error, but it won't stop your code, unless you set silent = TRUE
# you'll need to add control flow to keep your loop from breaking at the next function, however
if (class(recall_html) == 'try-error') {
next
} else {
prefecture <- recall_html %>%
html_nodes(xpath='//*[contains(concat( " ", @class, " " ), concat( " ", "column_ttl_small", " " ))]') %>%
html_text()