如何使用data.nba.net获取指定日期的NBA赛事数据与统计信息
NBA API 指定日期赛事数据查询方案
你当前的代码依赖today.json获取当日赛事链接,但休赛期该接口无有效数据,要实现指定日期查询,可直接构造对应日期的赛事数据接口路径,无需再请求today.json。NBA历史赛事数据的API格式为/prod/v1/YYYYMMDD/scoreboard.json,其中YYYYMMDD是你要查询的日期(比如2024年6月17日对应20240617)。
修改后的代码如下:
from requests import get from pprint import PrettyPrinter BASE_URL = "https://data.nba.net" printer = PrettyPrinter() def get_scoreboard(date_str): # 构造指定日期的赛事数据接口路径 scoreboard_url = f"/prod/v1/{date_str}/scoreboard.json" try: games = get(BASE_URL + scoreboard_url).json()['games'] for game in games: home_team = game['hTeam']['teamName'] home_score = game['hTeam']['score'] away_team = game['vTeam']['teamName'] away_score = game['vTeam']['score'] clock = game['clock'] if game['clock'] else "已结束" period = game['period']['current'] period_status = game['period']['status'] print("------------------------------------") print(f"{away_team} {away_score} vs {home_team} {home_score}") print(f"当前状态: {period_status}, 第{period}节, 剩余时间: {clock}") except KeyError: print(f"日期{date_str}无赛事数据或数据格式异常") except Exception as e: print(f"请求出错: {str(e)}") # 调用示例:查询2024年NBA总决赛G5的赛事数据 get_scoreboard("20240617")
代码说明:
- 直接通过传入的日期字符串
date_str(格式必须为YYYYMMDD)构造赛事数据接口,跳过today.json的依赖 - 优化了球队信息显示,提取了球队名称和比分,避免直接打印字典
- 处理了无赛事、接口异常等情况,增加容错性
- 对赛事状态(如已结束、进行中)做了友好展示
使用注意:
- 仅能查询NBA赛季内有赛事的日期,休赛期日期仍会返回无数据提示
- 日期格式必须严格遵循
YYYYMMDD,比如2023年10月24日要写成20231024
内容的提问来源于stack exchange,提问作者Nicolas
相关产品推荐
相关产品推荐

