R语言rvest循环调用遇HTTP 404错误,求解决方案
解决批量调用货币转换函数时的HTTP 404错误问题
核心问题分析
单独调用函数正常,但批量循环/映射时出现404错误,通常和无效请求URL、反爬机制触发、循环逻辑错误这三个原因有关,以下是针对性的解决思路和代码修正:
1. 无效货币对或URL格式问题
从easymarkets获取的货币代码可能存在非标准格式,或者部分货币对在Wise网站没有直接转换页面,导致生成的URL无效。此外,批量请求时如果没有提前校验URL可用性,会直接触发404错误。
修正方案:
- 在函数中加入HTTP请求状态校验,提前拦截无效URL并返回NA而非报错;
- 确保货币代码是Wise支持的3位标准格式(可提前过滤不符合长度的代码)。
修改后的转换函数:
library(tidyverse) library(rvest) library(httr) # 需要新增此包处理HTTP状态 currency_converter <- function(amount=1, from="eur", to="usd"){ node <- ".text-success" web_link <- paste0("https://wise.com/gb/currency-converter/", from, "-to-", to, "-rate") # 先校验URL是否可访问 resp <- GET(web_link) if (http_status(resp)$category != "Success") { warning(paste("跳过无效货币对:", from, "->", to)) return(NA_real_) } # 正常提取汇率逻辑 current_value <- read_html(resp) %>% html_nodes(node) %>% html_text() %>% str_split(pattern = " ") %>% pluck(1) %>% as.numeric() return(current_value * amount) }
2. 高频请求触发反爬机制
Wise会对短时间内的大量请求进行拦截,可能返回伪装的404错误。单独调用时请求频率低不会触发,但批量循环时很容易被识别为爬虫。
修正方案:
在函数中添加随机延迟,模拟人工访问间隔:
currency_converter <- function(amount=1, from="eur", to="usd"){ # 添加1-3秒随机延迟 Sys.sleep(runif(1, min=1, max=3)) # 后续原有逻辑保持不变... }
3. 循环逻辑错误
你的嵌套三层循环存在严重逻辑问题:会重复遍历所有from和to值,导致keep[i]被多次覆盖,最终传入大量无效的货币对组合,触发404。
修正方案:
直接遍历trainloop的每一行,传入对应参数:
# 替换原有嵌套循环 keep <- numeric(nrow(trainloop)) for(i in 1:nrow(trainloop)){ keep[i] <- currency_converter( amount = trainloop$amount[i], from = trainloop$from[i], to = trainloop$to[i] ) } # 或者用pmap时明确指定参数(避免cur_data()传入多余列) trainloop <- trainloop %>% mutate(ratio = pmap_dbl(list(amount, from, to), currency_converter))
额外优化建议
- 提前过滤相同货币的转换对(如EUR->EUR),减少无效请求:
trainloop <- trainloop %>% filter(from != to) - 处理函数返回的NA值,避免后续数据分析出错:
trainloop <- trainloop %>% drop_na(ratio)
内容的提问来源于stack exchange,提问作者Yann peacelover
相关产品推荐
相关产品推荐

