python写爬虫时需要捕获出错信息: try except模块

  1. 如果你肯花时间来了解我,你就会发现,你浪费了一点时间!
  2. 今天晚上写爬虫代码时候,需要了解出错信息,然后就自己调试了以下代码,最终找到了出错原因,然后呢直接贴代码讲吧!
   			 try:
                # //*[@id="J-items-content"]/div[5]/div/div[1]/div[2]/div[1]/div[1]
                # years = item.xpath('//*[@id="J-items-content"]/div[4]/div/div[1]/div[2]/div[1]/div[1]/text()')  # 只能定义单一年份
                years = item.xpath('.//div[@class="s-gold-supplier-year-icon"]/text()')  # 爬取年份(店铺经营的年份)
                products = item.xpath('.//div[@class="product"]')
                for product in products:
                    img = product.xpath('.//div/a/img/@src')
                    print('https:' + img)
                # print('years: ' + str(years[0]))

            except:
                print('oh my god, it is too hard!')
  • 这只是爬虫抓取数据的一小模块,然后因为报错跳到except那里,执行print语句,结果如下所示:
    在这里插入图片描述
  • 仅仅只是打印出了print语句,现在我需要了解到为什么报错,然后来更改代码,保证正常运行,于是就到网上查了下资料,修改的代码如下所示:
	           try:
                # //*[@id="J-items-content"]/div[5]/div/div[1]/div[2]/div[1]/div[1]
                # years = item.xpath('//*[@id="J-items-content"]/div[4]/div/div[1]/div[2]/div[1]/div[1]/text()')  # 只能定义单一年份
                years = item.xpath('.//div[@class="s-gold-supplier-year-icon"]/text()')  # 爬取年份(店铺经营的年份)
                products = item.xpath('.//div[@class="product"]')
                for product in products:
                    img = product.xpath('.//div/a/img/@src')
                    print('https:' + img[0])  # 错误之处 
                # print('years: ' + str(years[0]))

               except Exception as e:
              	 print('错误: %s' %e)
  • 结果它打印出来了报错的原因,直接贴图讲吧!
    在这里插入图片描述
  • 因为print(‘https:’ + img)这个语句中的img是一个列表,然后我把它直接与字符拼接起来,所有会得到报错信息,不能够讲str与list拼接,然后更改代码取出img[0]进行拼接最后成功运行了代码!
  • 最关键的代码语句更改如下:
 except Exception as e:
                print('错误: %s' %e)
  • 好勒,心情不好去打两把游戏,突然发现刚才心情挺好的!
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值