如何抓取NBA数据?

时间:2019-11-02 17:44:30

标签: r web-scraping

我想将各联盟的新秀与每场得分(PPG)等统计数据进行比较。 ESPN和NBA有很多不错的表格可供选择(与Basketball-reference一样),但是我发现它们没有存储在html中,所以我不能使用rvest。对于上下文,我正在尝试抓取这样的表(from NBA):

https://i.stack.imgur.com/SdKjE.png

我正在尝试学习如何为此使用HTTR和JSON,但是我遇到了一些问题。我遵循了this post中的答案,但对我来说却没有用。

这是我尝试过的:

library(httr)
library(jsonlite)
coby.white <- GET('https://www.nba.com/players/coby/white/1629632')
out <- content(coby.white, as = "text") %>%
  fromJSON(flatten = FALSE)

但是,我得到一个错误:

Error: lexical error: invalid char in json text.
                                       <!DOCTYPE html><html class="" l
                     (right here) ------^

是否有更简便的方法可以从ESPN或NBA刮下一张桌子,还是有解决此问题的方法?

2 个答案:

答案 0 :(得分:1)

ppg和其他统计数据来自]

https://data.nba.net/prod/v1/2019/players/1629632_profile.json

和玩家信息,例如体重,身高

https://www.nba.com/players/active_players.json

因此,您可以使用jsonlite解析例如

library(jsonlite)

data <- jsonlite::read_json('https://data.nba.net/prod/v1/2019/players/1629632_profile.json')

刷新页面时,可以在“网络”选项卡中找到它们。看来您可以在网址中使用玩家ID来获取本赛季的其他玩家信息。

答案 1 :(得分:1)

您实际上可以使用rvest进行网络抓取,这是从Basketball Reference中抓取White的总计表的示例。在《体育参考》网站上不是页面第一张表的所有内容都列为注释,这意味着我们必须首先提取注释节点,然后提取所需的数据表。

library(rvest)
library(dplyr)

cobywhite = 'https://www.basketball-reference.com/players/w/whiteco01.html'

totalsdf =  cobywhite %>%
read_html %>%
html_nodes(xpath = '//comment()') %>%
html_text() %>%
paste(collapse='') %>%
read_html() %>% 
html_node("#totals") %>% 
html_table()