2 u014567013 u014567013 于 2014.11.27 17:10 提问

Python 爬虫 index溢出

import urllib2
import re
from xlsxwriter.workbook import Workbook
from io import BytesIO
import json

workbook = Workbook('images.xlsx')
print "FETCHING YHD ..."
u = urllib2.urlopen('http://www.yhd.com/')
data = u.read()

ol_tag = re.findall(r'

.*?', data, flags = re.DOTALL)
li_tag = re.findall(r'', ol_tag[0], flags = re.DOTALL)

yhd_link = []
for item in li_tag:
link = re.findall(r'(?<=wi=").*?(?=")', item)
yhd_link += link

yhd_href_link = []
for item in li_tag:
link = re.findall(r'(?<=href=").*?(?=")', item)
yhd_href_link += link

worksheet = workbook.add_worksheet('yhd')

print "Total: " + str(len(yhd_link))
for i in range(len(yhd_link)):
print "yhd => Downloading Picture " + str(i+1)
image_data = BytesIO(urllib2.urlopen(yhd_link[i]).read())
if i % 4 == 0:
worksheet.set_row(i, 240)
else:
worksheet.set_row(i, 120)
worksheet.insert_image('A' + str(i+1), yhd_link[i], {'image_data': image_data, 'url': yhd_href_link[i]})

print "COMPLETE YHD ..."
workbook.close()

Traceback (most recent call last):
File "C:\Python27\project\banner\banneryhd.py", line 16, in
li_tag = re.findall(r'', ol_tag[0], flags = re.DOTALL)
IndexError: list index out of range

1个回答

mmzmagic
mmzmagic   2014.12.03 11:35
已采纳

ol_tag = re.findall(r'.*?', data, flags = re.DOTALL)

这里如果没有找到结果下一句话里的ol_tag[0] 就会导致索引错误, 所以你应该加保护语句, 没找到就给出相应的提示

li_tag = re.findall(r'', ol_tag[0], flags = re.DOTALL)

u014567013
u014567013 非常感谢您
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!