首页 > 解决方案 > 为什么我收到 IndexError:列表索引超出范围?

问题描述

为什么我会收到此错误?

motModel = motordata.get('displayAttributes')[1]['value'] or None
IndexError: list index out of range

我正在抓取汽车列表,对于这个特定的列表,列表中只有 1 项。换句话说motordata.get('displayAttributes')[0],存在但motordata.get('displayAttributes')[1]不存在。

我认为i in range(len(my_list))如果键存在,则使用它会返回一个值,如果不存在,则继续使用下一个键/项目。

my_list = motordata['displayAttributes']

for i in range(len(my_list)):
    motMake = motordata.get('displayAttributes')[0]['value'] or None
    motModel = motordata.get('displayAttributes')[1]['value'] or None
    motYear = motordata.get('displayAttributes')[2]['value'] or None
    motMilage = motordata.get('displayAttributes')[3]['value'] or None
    motFuel = motordata.get('displayAttributes')[4]['value'] or None

标签: pythonscrapy

解决方案


这个循环确实没有超出列表的范围:

for i in range(len(my_list)):

在该循环中,您可以i安全地使用作为索引访问列表元素。但这不是你在做的,你使用的是硬编码的索引值:

motMake = motordata.get('displayAttributes')[0]['value'] or None
motModel = motordata.get('displayAttributes')[1]['value'] or None
motYear = motordata.get('displayAttributes')[2]['value'] or None
motMilage = motordata.get('displayAttributes')[3]['value'] or None
motFuel = motordata.get('displayAttributes')[4]['value'] or None

因此,“对于列表中的每个项目”,您是在告诉代码“给我前 5 个项目”。您明确地告诉代码访问您知道只有一项的列表中的第二项。所以,你得到一个例外。

看起来您根本不想要循环,因为您从未实际使用i并且总是在循环中覆盖相同的变量。相反,请在访问 5 个硬编码索引值中的每一个之前检查列表的长度。像这样的东西:

my_list = motordata['displayAttributes']
length = len(my_list)

if length > 0:
    motMake = motordata.get('displayAttributes')[0]['value']
if length > 1:
    motModel = motordata.get('displayAttributes')[1]['value']
if length > 2:
    motYear = motordata.get('displayAttributes')[2]['value']
if length > 3:
    motMilage = motordata.get('displayAttributes')[3]['value']
if length > 4:
    motFuel = motordata.get('displayAttributes')[4]['value']

推荐阅读