使用R抓取Baseball Savant本垒打排行榜表格失败,求帮助
解决R抓取MLB棒球数据表格的问题
问题描述
尝试抓取MLB Home Runs排行榜的表格,使用rvest编写的代码无法成功提取数据,原代码如下:
install.packages("rvest") install.packages("dplyr") library(rvest) library(dplyr) url <- "https://baseballsavant.mlb.com/leaderboard/home-runs?player_type=Batter&team=&min=0&cat=adj_xhr&year=2020" # Read the webpage webpage <- read_html(url) # Extract the table table <- webpage %>% html_node(xpath = '//*[@id="homeruns"]/table') %>% html_table() # View the table print(table)
原因分析
该网页的表格数据是动态加载的,read_html()只能获取页面初始的静态HTML,而实际表格内容是通过后端API异步加载的,因此直接解析静态HTML无法获取完整的表格数据。
解决方案
方法1:直接调用API接口(推荐)
通过浏览器开发者工具可定位到数据的API接口,直接请求接口获取JSON数据后转换为数据框,效率更高:
library(jsonlite) library(dplyr) # 对应原网页筛选条件的API接口 api_url <- "https://baseballsavant.mlb.com/leaderboard/custom?year=2020&type=batter&filter=&sort=1&sortDir=desc&min=0&selections=player_adj_xhr,player_name,player_id,player_team,player_pos,player_hr,player_adj_xhr,player_ab,player_xhr_avg,player_xhr_max,player_xhr_min,player_xhr_std&chart=false&x=player_adj_xhr&y=player_adj_xhr&r=no&chartType=beeswarm" # 获取JSON数据并转换为数据框 data <- fromJSON(api_url) %>% as.data.frame() # 查看数据 print(data)
方法2:使用RSelenium模拟浏览器加载
如果需要模拟完整的浏览器渲染流程,可使用RSelenium(需提前安装对应浏览器驱动,如ChromeDriver):
library(RSelenium) library(rvest) library(dplyr) # 启动Chrome浏览器 driver <- rsDriver(browser = "chrome", port = 4567L) remote_driver <- driver[["client"]] # 访问目标网页 remote_driver$navigate("https://baseballsavant.mlb.com/leaderboard/home-runs?player_type=Batter&team=&min=0&cat=adj_xhr&year=2020") # 等待页面加载完成(可根据网络情况调整等待时间) Sys.sleep(3) # 获取页面HTML并解析表格 webpage <- remote_driver$getPageSource()[[1]] %>% read_html() table <- webpage %>% html_node("#homeruns table") %>% html_table() # 查看表格 print(table) # 关闭浏览器及驱动 remote_driver$close() driver$server$stop()
内容的提问来源于stack exchange,提问作者Anthony Amico
相关产品推荐
相关产品推荐

