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

Python调用GraphQL API返回HTML无法获取JSON数据如何解决?

解决方法

核心原因

  • 你调用的是The Graph协议部署的GraphQL节点,节点默认会根据请求头返回对应内容:未指定Accept: application/json时,会返回GraphQL可视化查询界面的HTML内容,也就是你拿到的响应结果
  • 部分节点会校验User-Agent请求头,缺失合法UA会被反爬策略拦截返回错误页面
  • 你的GET请求路径缺少/graphql后缀,也是返回HTML的诱因之一

正确请求代码

GET请求版本

import requests

query = {
    'query': '{saleAuctions(allowedAddresses: ["0xdc65d63cdf7b03b95762706bac1b8ee0af130e8b", "0x0000000000000000000000000000000000000000"]) {id}}'
}
headers = {
    "Accept": "application/json",
    "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"
}
r = requests.get(
    'https://graph.defikingdoms.com/subgraphs/name/defikingdoms/apiv5/graphql', 
    params=query,
    headers=headers
)

print(r.headers['content-type'])
# 直接获取JSON结果
print(r.json())

POST请求版本(更推荐,避免GET参数长度限制)

import requests

query = {
    'query': '{saleAuctions(allowedAddresses: ["0xdc65d63cdf7b03b95762706bac1b8ee0af130e8b", "0x0000000000000000000000000000000000000000"]) {id}}'
}
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "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"
}
r = requests.post(
    'https://graph.defikingdoms.com/subgraphs/name/defikingdoms/apiv5',
    json=query,
    headers=headers
)

print(r.headers['content-type'])
print(r.json())

两种方式都可以正常获取到application/json类型的响应结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:45:04