【问题标题】:Scraping table of NBA stats with rvest带有 rvest 的 NBA 统计数据抓取表
【发布时间】:2017-05-26 23:10:18
【问题描述】:
我想用 rvest 抓取一张 NBA 球队统计数据表,我尝试过使用:
-
表格元素
library(rvest)
url_nba <- "http://stats.nba.com/teams/advanced/#!?sort=TEAM_NAME&dir=-1"
team_stats <- url_nba %>% read_html %>% html_nodes('table') %>% html_table
-
xpath(通过谷歌浏览器检查)
team_stats <- url_nba %>%
read_html %>%
html_nodes(xpath="/html/body/main/div[2]/div/div[2]/div/div/nba-stat-table/div[1]/div[1]/table") %>%
html_table
-
css 选择器(通过 mozilla 检查):
team_stats <- url_nba %>%
read_html %>%
html_nodes(".nba-stat-table__overflow > table:nth-child(1)") %>%
html_table
但没有运气。任何帮助将不胜感激。
【问题讨论】:
标签:
css
r
web-scraping
rvest
【解决方案1】:
这个问题和这个问题很相似:How to select a particular section of JSON Data in R?
您请求的数据未存储在 html 代码中,因此使用 rvest 失败。请求的数据存储为 XHR 文件,可以直接访问:
library(httr)
library(jsonlite)
nba<-GET('http://stats.nba.com/stats/leaguedashteamstats?Conference=&DateFrom=&DateTo=&Division=&GameScope=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Advanced&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2016-17&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=' )
一旦数据加载到 nba 变量中,使用 httr 和 jsonlite 清理数据:
#access the data
out<- content(nba, as="text") %>% fromJSON(flatten=FALSE)
#convert into dataframe.
# str(out) to determine the structure
df<-data.frame(out$resultSets$rowSet)
names(df)<-out$resultSets$headers[[1]]
我强烈建议阅读我上面链接的问题的答案。