python - IndexError:列表索引超出范围 - API
问题描述
嗨,我正在生成data to csv
基于Opensea API
. 问题是我受到 API 列表大小的限制。有没有办法解决这个问题?
这是我的代码:
r = requests.get('https://api.opensea.io/api/v1/assets?collection=bit birds&order_direction=asc&offset=' + (str(x)) + '&limit=1')
jsonResponse = r.json()
name = jsonResponse['assets'][0]['name']
description = jsonResponse['assets'][0]['description']
print('Name: ' + name)
print('Description: ' + str(description))
我得到这个错误:
Traceback (most recent call last): File
"d:\generate-bitbirds-main\generate-bitbirds-main\bird_data\bitbird_generation_script_w_csv4.py",
line 1855, in <module>
name = jsonResponse['assets'][0]['name'] IndexError: list index out of range
解决方案
使用 API 时,最好先检查请求是否成功,然后再访问响应。您可以先调用r.raise_for_status()并处理错误情况。然后在访问列表之前,先检查它是否不为空。
r = requests.get(...)
try:
r.raise_for_status() # Check if the request was successful
jsonResponse = r.json() # Check if the response is in JSON format
except requests.HTTPError, JSONDecodeError:
# Handle error scenario
else:
if jsonResponse['assets']: # Check first if there are assets returned
# Proceed as usual
name = jsonResponse['assets'][0]['name']
description = jsonResponse['assets'][0]['description']
else: # This means that the assets are empty. Depending on your use case logic, handle it accordingly.
# Handle empty assets scenario
推荐阅读
- awk - 用冒号分隔时使用 awk 来划分列
- python - 合并具有重叠线性范围的记录
- python - Python3如何同时进行并行输入和输出?
- python - 在谷歌表格中创建非基于 HTTP 的超链接是否有任何解决方法/替代方法?
- rabbitmq - 难以从 SCDF 流组件连接到 PCF RabbitMQ 实例
- java - 从主类中的 Rectangle 类调用方法
- amazon-web-services - 在 AWS CostExplorer 中按 CloudFront 分配 ID 对使用情况进行分组
- python - 尝试写入 S3 时,Docker 容器中的 Spark 返回“任何本地目录中没有可用空间”
- android - 在 Jetpack Compose 上滚动时折叠导航底部栏
- javascript - 如何确保有头和无头浏览器的行为方式相同?