首页 > 解决方案 > 使用 R rvest 抓取表格

问题描述

作为一个自学 rvest 的例子,我试图抓取一个网站来抓取已经以表格格式写入的数据。唯一的问题是我无法获得基础表数据的输出。

我唯一真正需要的是玩家专栏。

library(tidyverse)
library(rvest)


base <- "https://www.milb.com/stats/"
base2 <- "?page="
base3 <- "&playerPool=ALL"

html <- read_html(paste0(base,"pacific-coast/","2017",base2,"2",base3))

html2 <- html %>% html_element("#stats-app-root")
html3 <- html2 %>% html_text("#stats-body-table player") 

https://www.milb.com/stats/pacific-coast/2017?page=2&playerPool=ALL(查看实际示例网址的简便方法)

“HTML 2”似乎可以工作,但我有点不知道从那里做什么。几次不同的尝试都碰壁了。

一旦这可行,我将用数字替换文本并执行一些 for 循环(这看起来很简单)。

标签: rweb-scrapingrvest

解决方案


如果您在 chrome 中“检查”页面,您会看到它正在调用下载 json 文件。自己做就行了...

library(jsonlite)

data <- fromJSON("https://bdfed.stitch.mlbinfra.com/bdfed/stats/player?stitch_env=prod&season=2017&sportId=11&stats=season&group=hitting&gameType=R&offset=25&sortStat=onBasePlusSlugging&order=desc&playerPool=ALL&leagueIds=112")
df <- data$stats

head(df)

 year playerId       playerName   type rank   playerFullName
1 2017   643256      Adam Cimber player   26      Adam Cimber
2 2017   458547   Vladimir Frias player   27   Vladimir Frias
3 2017   643265   Garrett Cooper player   28   Garrett Cooper
4 2017   542979     Keon Broxton player   29     Keon Broxton
5 2017   600301    Taylor Motter player   30    Taylor Motter
6 2017   624414 Christian Arroyo player   31 Christian Arroyo
...

推荐阅读