Python爬取2023新PGA Tour赛事特定数据失败求助
问题诊断与修复方案
核心错误点
- GraphQL查询语法完全错误:你的query字段调用格式不符合规范,直接堆砌变量而非通过参数传递,且缺失大量闭合语法符号
- 变量类型不匹配:
includeWithdrawn和changesOnly定义为Boolean类型,但你传入了数字0和字符串"false",需改用布尔值false - 查询片段缺失:代码中使用了
...FieldPlayer片段,但未定义该片段的具体字段,服务器无法解析
修正后的完整代码
import requests X_API_KEY = "da2-gsrx5bibzbb4njvhl7t37wqyl4" FIELD_ID = "R2023540" payload = { "operationName": "Field", "variables": { "fieldId": FIELD_ID, "includeWithdrawn": False, "changesOnly": False }, "query": """ query Field($fieldId: ID!, $includeWithdrawn: Boolean, $changesOnly: Boolean) { field(fieldId: $fieldId, includeWithdrawn: $includeWithdrawn, changesOnly: $changesOnly) { tournamentName id lastUpdated message players { ...FieldPlayer teammate { id alphaSort firstName lastName shortName displayName amateur favorite country countryFlag headshot qualifier alternate withdrawn status owgr rankingPoints } } } } fragment FieldPlayer on Player { id alphaSort firstName lastName shortName displayName amateur favorite country countryFlag headshot qualifier alternate withdrawn status owgr rankingPoints } """ } page = requests.post( "https://orchestrator.pgatour.com/graphql", json=payload, headers={"x-api-key": X_API_KEY} ) page.raise_for_status() # 先打印完整响应,便于调试 response_data = page.json() print(response_data) # 安全提取数据 if "data" in response_data and "field" in response_data["data"]: data_field = response_data["data"]["field"]["players"] print(data_field) else: print("API返回错误信息:", response_data.get("errors"))
调试建议
- 发送请求后优先打印完整响应内容,查看是否存在
errors字段,里面会包含服务器返回的具体错误提示 - 从开发者工具复制GraphQL查询时,务必复制完整内容,包括所有片段定义和参数格式
- 严格匹配变量类型:Boolean类型只能传入
true或false,禁止使用字符串或数字替代
内容的提问来源于stack exchange,提问作者Philby_Walsh
相关产品推荐
相关产品推荐

