python解决问题-IndexError: list index out of range

@[python](IndexError: list index out of range)

python解决问题-IndexError: list index out of range

在这里插入图片描述

问题详解:

错误:
在这里插入图片描述
错误的地方:
在这里插入图片描述

解决方法链接:https://www.jianshu.com/p/f1b58ec12b72

正文

  1. 错误原因 :爬虫在做xpath时匹配到空值,正则表达式匹配的位置introduction有空值。
  2. 解决步骤1:对空值进行判断
if introdution:
               movie={'name':name , 'director_actor':director_actor , 'info':info, 'score':score , 'evaluator':evaluator, 'introdution':introdution}
           else:
               movie={'name':name , 'director_actor':director_actor , 'info':info, 'score':score , 'evaluator':evaluator, 'introdution':None}
  1. 解决步骤2:加上try…except 错误机制跳过tr空值
try:
            # name = li.xpath('//*[@id="content"]/div/div[1]/ol/li[1]/div/div[2]/div[1]/a/span[1]')
            name = li.xpath(".//a/span[@class='title']/text()")[0]
            director_actor=li.xpath(".//div[@class='bd']/p/text()")[0].strip()
            info=li.xpath(".//div[@class='bd']/p/text()")[1].strip()
            score = li.xpath(".//div[@class='star']/span[2]/text()")[0]
            evaluator = li.xpath(".//div[@class='star']/span[4]/text()")[0]
            introdution = li.xpath(".//p[@class='quote']/span/text()")[0]

            if introdution:
                movie={'name':name , 'director_actor':director_actor , 'info':info, 'score':score , 'evaluator':evaluator, 'introdution':introdution}
            else:
                movie={'name':name , 'director_actor':director_actor , 'info':info, 'score':score , 'evaluator':evaluator, 'introdution':None}

            img = li.xpath(".//div[@class='pic']/a/img/@src")[0]
    
            movies.append(movie)
            imgUrl.append(img)
        except IndexError:
            pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值