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

PrizePicks API爬取无球员姓名:如何修改代码获取球员姓名?

问题描述

我用以下Python代码调用PrizePicks API爬取数据,但结果里没有球员姓名,怎么修改才能拿到球员姓名?

import requests
import pandas as pd
pp_props_url = 'https://api.prizepicks.com/projections?league_id=7&per_page=250&single_stat=true'
headers = {
'Connection': 'keep-alive',
'Accept': 'application/json; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
'Access-Control-Allow-Credentials': 'true',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'cors',
'Referer': 'https://app.prizepicks.com/',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9'}

response = requests.get(url=pp_props_url, headers=headers).json()
df = pd.json_normalize(response,
                       record_path =['data'])

df.to_csv('player_props_20221030.csv')
解决方案

PrizePicks的API响应里,球员姓名不在data数组的投影数据中,而是存放在included数组里的player类型条目里。你需要把投影数据和球员数据通过球员ID关联起来,步骤如下:

  1. 提取投影数据时保留球员ID字段
  2. 从included数组中提取球员的ID和姓名,建立映射关系
  3. 将映射关系合并到投影数据框中,得到球员姓名

修改后的完整代码:

import requests
import pandas as pd

pp_props_url = 'https://api.prizepicks.com/projections?league_id=7&per_page=250&single_stat=true'
headers = {
    'Connection': 'keep-alive',
    'Accept': 'application/json; charset=UTF-8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
    'Access-Control-Allow-Credentials': 'true',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'cors',
    'Referer': 'https://app.prizepicks.com/',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9'
}

response = requests.get(url=pp_props_url, headers=headers).json()

# 提取投影数据,保留球员ID字段
projections_df = pd.json_normalize(response['data'])

# 提取球员数据,筛选type为player的条目,建立ID到姓名的映射
players_df = pd.json_normalize(response['included'])
players_df = players_df[players_df['type'] == 'player']
player_id_to_name = players_df.set_index('id')['attributes.name'].to_dict()

# 将球员姓名合并到投影数据中
projections_df['player_name'] = projections_df['relationships.player.data.id'].map(player_id_to_name)

# 保存结果
projections_df.to_csv('player_props_with_names_20221030.csv', index=False)
关键说明
  • API响应的included数组包含了所有关联资源,其中type为player的条目存储了球员的详细信息,包括attributes.name字段(球员姓名)
  • 投影数据中的relationships.player.data.id是当前投影对应的球员ID,通过这个ID可以从映射字典中匹配到对应的姓名
  • 最后新增的player_name字段就是你需要的球员姓名,会被写入到输出的CSV文件中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:47:00