Python调用Opensea API提取sell_orders中current_price报TypeError如何解决
问题原因
d['sell_orders']是列表结构,不是字典结构,不能直接用字符串键current_price访问列表元素。你需要先定位到列表中对应的挂单对象,再提取目标字段。
解决代码
基础版本(默认取每个资产第一个挂单的current_price,自动忽略无挂单的资产)
import requests import re import json p={ 'collection': 'wisecards', 'limit':5 } g=requests.get("https://api.opensea.io/api/v1/assets?offset=0",params=p) x = g.json() # 先判断sell_orders非空,再取第一个元素的current_price price = [d['sell_orders'][0]['current_price'] for d in x['assets'] if d.get('sell_orders')] print(price)
兼容版本(无挂单的资产对应位置填充None,避免条目数量不匹配)
price = [d['sell_orders'][0]['current_price'] if d.get('sell_orders') else None for d in x['assets']]
如果需要提取所有挂单的current_price而不只是第一个,可以再加一层遍历:
price = [order['current_price'] for d in x['assets'] for order in d.get('sell_orders', [])]
内容的提问来源于stack exchange,提问作者Robert Tudor
相关产品推荐
相关产品推荐

