[英]Multiple errors index and http errors returned when running loop in Rstudio using rvest
我正在尝试计算每个国家/地区之间的飞行时间,希望为我正在研究的防欺诈工具创建参数。
我正在使用的网站 url 是https://www.travelmath.com/flying-time/from/Canada/to/Germany
我拥有的第三列是用所有可能的组合替换两个国家/地区参考。
我正在尝试使用带有循环的 RVEST 来执行此操作,但不断收到各种错误。 我查看了堆栈以尝试使用其他解决方案来解决我的问题,但遇到了许多问题。 最后,我正在尝试创建一个循环,该循环不会在简短的 window 中使用 55225 个请求来炸毁我正在查询的网站。
这是我尝试过的最新解决方案,但重复出现以下错误
我尝试重新安排我的数据框并处理起点和终点的替换。
我尝试使用 Rselenium 来执行此操作,但也遇到了其他问题。
我尝试重新格式化其他类似问题的解决方案,但仍然收到错误。
tables <- list()
index <- 1
for (i in CountryPairs){
try(
{
url <- paste0("https://www.travelmath.com/flying-time/from/",i)
table <- url %>%
read_html()%>%
html_nodes("#flyingtime")
tables[index] <- table
index <- index +1
}
)
}
df<-do.call("rbind",tables)
open.connection 中的错误(x,“rb”):HTTP 错误 400。
表[索引] <- 表中的错误:替换的长度为零
我列出了一个国家列表来构建您的CountryPairs
变量,并使用您的代码来提出这个问题。 tables
变量填充了飞行时间作为字符向量。 由于您遇到了一些 HTTP 400 错误,我认为问题在于您生成CountryPairs
变量的方式,从而产生了错误的请求。
library(dplyr)
library(rvest)
# Vector of countries
countries <- c(
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola",
"Argentina",
"Armenia",
"Australia",
"Austria",
"Azerbaijan"
)
# Build all combinations of two countries
countries_combinations <- combn(countries, 2)
# Build the country pairs as "Country1/to/Country2" for the request to travelmath
country_pairs <- apply(countries_combinations, 2, function(x) paste(x, collapse = "/to/"))
tables <- list()
index <- 1
for (c_pair in country_pairs){
try(
{
url <- paste0("https://www.travelmath.com/flying-time/from/", c_pair)
# Get the flight time from the #flyingtime h3 tag
table <- url %>%
read_html %>%
html_nodes("#flyingtime") %>%
html_text
tables[index] <- table
index <- index + 1
}
)
}
编辑:要删除未使用的连接,我发现的唯一解决方案是在这个堆栈溢出线程上。 您可以致电 function:
CatchupPause <- function(secs){
Sys.sleep(secs) # pause to let connection work
closeAllConnections()
gc()
}
在你的for
循环结束时,使用secs = 3
,使 sur 连接正确关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.