为何触发IndexError: list index out of range?汽车列表爬取代码问题
解决Python索引越界的问题
首先得指出你代码里的核心问题:你写的for循环完全没发挥作用——循环里根本没用到变量i,每次循环都硬编码访问[0]到[4]这些固定索引,不管displayAttributes列表实际有多少元素,这才是触发IndexError的根源。
针对你的场景,有两种比较稳妥的解决方案:
方案1:安全按索引访问(适合属性位置固定的情况)
先获取displayAttributes列表,然后逐个检查列表长度是否足够,再取值,不够的话就设为None:
# 先获取列表,避免KeyError,默认空列表 display_attrs = motordata.get('displayAttributes', []) # 逐个检查长度再取值,防止索引越界 motMake = display_attrs[0]['value'] if len(display_attrs) > 0 else None motModel = display_attrs[1]['value'] if len(display_attrs) > 1 else None motYear = display_attrs[2]['value'] if len(display_attrs) > 2 else None motMilage = display_attrs[3]['value'] if len(display_attrs) > 3 else None motFuel = display_attrs[4]['value'] if len(display_attrs) > 4 else None
这种方式简单直接,适合你确定属性在列表里的位置是固定的(比如第0个永远是品牌,第1个永远是型号),但可能存在缺失的情况。
方案2:转成字典后按key取值(更健壮,推荐)
如果displayAttributes里的每个元素都有一个标识属性(比如key字段,类似{'key': 'make', 'value': '本田'}这种结构),那建议先把列表转成字典,再通过key取值,这样不管属性顺序如何、是否缺失,都不会报错:
# 把displayAttributes转成key:value的字典 attr_dict = {item.get('key'): item.get('value') for item in motordata.get('displayAttributes', [])} # 按key取值,不存在则返回None motMake = attr_dict.get('make') motModel = attr_dict.get('model') motYear = attr_dict.get('year') motMilage = attr_dict.get('milage') motFuel = attr_dict.get('fuel')
这种方式更灵活,哪怕列表里的元素顺序变了,或者某个属性缺失,都能正常获取到存在的值,不存在的自动返回None。
最后再提一句:你原来的for循环完全是多余的,因为没有利用循环变量i来动态访问索引,反而重复执行相同的赋值操作,建议删掉那个循环哦。
内容的提问来源于stack exchange,提问作者billiam
相关产品推荐
相关产品推荐

