最近我正在开发一个小型爬虫,用于下载指定url上的图片。
我使用urllib2中的openurl()函数,并结合f.open()/f.write()进行操作:
以下是代码片段:
# the list for the images' urls
imglist = re.findall(regImg,pageHtml)
# iterate to download images
for index in xrange(1,len(imglist)+1):
img = urllib2.urlopen(imglist[index-1])
f = open(r'E:\OK\%s.jpg' % str(index), 'wb')
print('To Read...')
# potential timeout, may block for a long time
# so I wonder whether there is any mechanism to enable retry when time exceeds a certain threshold
f.write(img.read())
f.close()
print('Image %d is ready !' % index)
在上面的代码中,img.read() 可能会阻塞很长时间,我希望在这种情况下进行一些重试/重新打开图像 URL 操作。
我还关注以上代码的效率问题,如果要下载的图片数量较大,则使用线程池下载似乎更好。
有什么建议吗?提前感谢您。
附言:我发现 img 对象上的 read() 方法可能会导致阻塞,因此仅向 urlopen() 添加超时参数似乎是无用的。但我发现文件对象没有超时版本的 read()。对此有什么建议吗?非常感谢。