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

如何从Binance P2P API的JSON数据中获取价格?代码报错求解

问题分析与解决

1. NameError: name 'response' is not defined

你将POST请求的结果赋值给了变量r,但在main()函数里错误使用了未定义的response变量。另外,把请求逻辑封装到函数内部比放在全局作用域更规范。

2. 交易价格提取问题

Binance P2P API返回的JSON中,data字段下的adv数组包含所有交易广告信息,每个广告项的price字段就是交易价格。你当前循环里用了未定义的adv变量,应该遍历你赋值的bids(即adv数组)。

修正后的完整代码

import requests  # 必须导入requests库

headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "content-type": "application/json",
    "Host": "p2p.binance.com",
    "Origin": "https://p2p.binance.com",
    "Pragma": "no-cache",
    "TE": "Trailers",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0"
}

data = {
  "asset": "USDT",
  "fiat": "RUB",
  "merchantCheck": False,
  "page": 1,
  "payTypes": ["TinkoffNew"],
  "publisherType": None,
  "rows": 1,
  "tradeType": "SELL"
}

def main():
    # 将请求逻辑移到函数内部,结构更清晰
    r = requests.post('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', headers=headers, json=data)
    r.raise_for_status()  # 可选:检查请求是否成功
    
    # 解析JSON响应
    response_data = r.json()
    adv_list = response_data["data"]["adv"]  # 获取广告列表
    
    # 提取并处理交易价格
    prices = []
    for item in adv_list:
        price = item["price"]
        prices.append(price)
        print(f"当前交易价格: {price}")
    
    return prices

if __name__ == "__main__":
    main()

关键修正说明

  • 新增import requests:避免因未导入库触发的NameError。
  • 替换response为r:使用正确的变量名访问请求结果。
  • 遍历adv_list:修正未定义adv的错误,正确遍历广告数组。
  • 收集并打印价格:将提取的价格存入列表并输出,直观展示结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:27:26