r - 使用 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 循环(这看起来很简单)。
解决方案
如果您在 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
...
推荐阅读
- java - 从 Spring 应用程序中的代码跟踪 bean 创建
- laravel - laravel 更新数据质量分配加 ch
- java - 投射可选或流的内容
- html - 在 .Net 资源中使用 HTML 实体
- r - 以原始方式打开 R 控制台,而不是在 linux 终端中
- sql-server - 在特定天数内选择一些数据
- mongodb - 如何根据 MongoDB 中的日期范围过滤数据?
- javascript - 在 for_loop 中使用 getElementsByClassName 不能正常工作
- c# - Ef-Core - 我可以使用什么正则表达式在 Db 拦截器中用 nolock 替换表名
- jenkins - 如何运行用户可以输入日期和时间值的 Jenkins 作业?