使用R语言rvest包爬取东方财富网分页基金表格的问题求助
问题1报错原因
你遇到的报错本质是目标表格属于客户端动态渲染内容,初始静态HTML源码中不存在该表格元素,rvest默认只能抓取静态HTML内容,因此匹配不到对应节点返回空列表,取下标自然越界。
解决思路
优先选择直接调用后端数据接口的方案,无需模拟浏览器渲染,效率更高:
步骤1:接口请求与单页数据解析
直接请求对应官方数据接口即可拿到结构化数据,代码示例:
# 加载依赖包 library(httr) library(jsonlite) library(dplyr) # 配置基础参数 fund_code <- "510300" base_url <- "http://api.fund.eastmoney.com/f10/lsjz" # 伪装请求头避免被拦截 request_headers <- c( "Referer" = "https://fundf10.eastmoney.com/" ) # 单页请求测试 resp <- GET(base_url, query = list( callback = "", fundCode = fund_code, pageIndex = 1, pageSize = 50 # 可自定义每页返回条数,最大支持1000左右 ), add_headers(.headers = request_headers)) # 解析返回的JSON数据 result_json <- fromJSON(content(resp, "text", encoding = "UTF-8")) # 提取单页表格数据 single_page_data <- result_json$Data$LSJZList
步骤2:全量分页数据爬取与合并
通过循环修改请求参数中的页码,即可批量获取所有页面数据并合并:
# 先获取总数据量计算总页数 total_count <- result_json$TotalCount page_size <- 100 # 每页设置100条可减少请求次数 total_page <- ceiling(total_count / page_size) # 初始化空数据框存储全量结果 all_fund_data <- data.frame() # 循环爬取所有页 for (page in 1:total_page) { # 每次请求加1秒延迟,避免请求频率过高被限制 Sys.sleep(1) current_resp <- GET(base_url, query = list( callback = "", fundCode = fund_code, pageIndex = page, pageSize = page_size ), add_headers(.headers = request_headers)) current_json <- fromJSON(content(current_resp, "text", encoding = "UTF-8")) current_page_data <- current_json$Data$LSJZList all_fund_data <- bind_rows(all_fund_data, current_page_data) }
如果遇到找不到数据接口的动态页面场景,也可以使用
RSelenium包启动无头浏览器,等待页面渲染完成后再用rvest提取节点,该方案兼容性更强但运行速度更慢。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

