【发布时间】:2012-11-24 17:43:44
【问题描述】:
最近我正在开发一个小型爬虫,用于在 url 上下载图像。
我在 urllib2 中使用 openurl() 和 f.open()/f.write():
这里是sn-p的代码:
# 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() 的超时版本。对此有什么建议吗?非常感谢。
【问题讨论】:
标签: python multithreading web-crawler urllib2