You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用httr2爬取NBA对手投篮数据报错,求正确请求URL

解决NBA对手投篮数据爬取的URL问题

你遇到的错误是因为当前的req_url指向的是NBA的前端展示页面,返回的是HTML内容,而你的代码试图解析JSON数据,所以报错。NBA统计页面的实际数据是通过后端API接口返回的,需要替换成对应的API地址。

正确的API URL及参数

正确的请求地址是NBA官方的统计API端点,结合你需要的"Pullups"(急停跳投)和常规赛数据,完整的req_url应该是:

req_url <- "https://stats.nba.com/stats/leaguedashteamshotopponent?GeneralRange=Pullups&SeasonType=Regular%20Season&Season=2023-24&PerMode=PerGame"

参数说明:

  • GeneralRange=Pullups:指定筛选急停跳投数据
  • SeasonType=Regular%20Season:常规赛(注意空格转义为%20)
  • Season=2023-24:指定赛季(可根据需要修改,比如2022-23)
  • PerMode=PerGame:按场均数据统计(可选Totals等其他模式)

调整后的完整代码

需要确保请求头足够完整,避免被API拦截,调整后的代码如下:

library(httr2)
library(janitor)
library(dplyr)

req_url <- "https://stats.nba.com/stats/leaguedashteamshotopponent?GeneralRange=Pullups&SeasonType=Regular%20Season&Season=2023-24&PerMode=PerGame"

json <- 
  request(req_url) |>
  req_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") |>
  req_headers(
    "Accept" = "application/json, text/plain, */*",
    "Origin" = "https://www.nba.com",
    "Referer" = "https://www.nba.com/stats/",
    "Connection" = "keep-alive"
  ) |>
  req_perform() |>
  resp_body_json() 

hdr <- json$resultSets$headers

# 构建清洗后的列名
clean_names <- 
  c(
    rep("", hdr[[1]]$columnsToSkip), 
    rep(unlist(hdr[[1]]$columnNames), each = 3)
  ) |>
  paste(unlist(hdr[[2]]$columnNames)) |>
  janitor::make_clean_names()

# 转换为数据框
data <- json$resultSets$rowSet |>
  lapply(setNames, clean_names) |>
  dplyr::bind_rows()

关键说明

  • NBA的stats API会验证请求头的合法性,所以Origin和Referer必须指向NBA官方域名,User-Agent要模拟真实浏览器。
  • 如果需要其他赛季或统计模式,只需修改URL中的Season和PerMode参数即可。

内容的提问来源于stack exchange,提问作者gimmethedata123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 08:50:56