【问题标题】:IndexError: list index out of range - APIIndexError:列表索引超出范围 - API
【发布时间】:2021-11-06 13:58:09
【问题描述】:

您好,我正在生成基于Opensea API 的随机data to csv 文件。问题是我受到 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

【问题讨论】:

  • 响应中的资产列表可能是空的。您无法从空列表中获取项目。
  • 将此作为运行脚本。该错误表明列表为空。对此我们无话可说,除了您需要在使用前检查数据或捕获异常并在这种情况下做任何您认为合理的事情。

标签: python index-error


【解决方案1】:

使用 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

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多