从PrizePicks抓取预测数据遇语法错误及CSV无内容问题求助
问题修复方案
一、先解决语法错误
你代码里有俩直接触发报错的语法问题:
- headers字典未闭合:定义headers的代码块末尾,闭合花括号
}被单独放在了代码块外,Python解析时会直接报错,把}移到headers键值对的末尾即可。 - 列表元素缺少逗号:
columns_list中,从"Team_Name"开始的后续元素之间都没加逗号,Python会将相邻字符串视为拼接操作,引发语法错误,给每个元素末尾加上逗号就能解决。
二、CSV仅显示表头的问题
直接把整个API响应赋值给DataFrame是错误的,PrizePicks的API返回是嵌套结构,真正的球员预测数据在response['data']字段中。此外你定义的列名需要和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() # 提取API返回的核心预测数据列表 projections = response.get('data', []) # 整理提取所需字段 player_props_data = [] for proj in projections: # 从嵌套结构中提取基础信息 league = proj['attributes']['league']['name'] league_id = proj['attributes']['league']['id'] market = proj['attributes']['market'] player_name = proj['attributes']['player']['name'] position = proj['attributes']['player']['position'] team = proj['attributes']['player']['team'] stat_type = proj['attributes']['stat_type'] line_score = proj['attributes']['line_score'] # 匹配统计字段与对应值 stats = { 'Points': None, 'Rebounds': None, 'Assists': None, 'Pts+Rebs+Asts': None, '3-Pt Made': None } stats[stat_type] = proj['attributes']['stat'] # 组装成字典并加入列表 player_props_data.append({ 'League': league, 'League_Id': league_id, 'Market': market, 'Name': player_name, 'Position': position, 'Team': team, 'Team_Name': team, # API中team与team_name字段内容一致,可按需调整 'Stat_Type': stat_type, 'Line_Score': line_score, **stats }) # 转换为DataFrame并保存为CSV pp_df = pd.DataFrame(player_props_data) pp_df.to_csv('player_props_20221030.csv', index=False)
三、修复说明
- 请求部分:先修正headers的语法问题,确保请求能正常发送并获取到数据。
- 数据提取:从API响应的
data字段中拿到真实的预测数据集合,遍历每个预测项,从嵌套的attributes结构中提取联赛、球员、统计类型等信息。 - 统计字段匹配:每个预测项仅对应一种统计类型,通过
stat_type将对应数值填入指定列,保证数据对应准确。 - 生成CSV:将整理好的字典列表转换为DataFrame,此时各列都会有对应数据,保存的CSV不再只有表头。
内容的提问来源于stack exchange,提问作者Eddie Chinea
相关产品推荐
相关产品推荐

