想实现一个抓取图片url,然后下载图片到本地去爬虫。想利用多线程的方法增加速度, 注:在不用多线程的情况下代码能够正确抓取URL。同时也能够把图片下载到指定文件夹
以下是代码,求解看一下哪个地方不正确,给予指正:
最起码的,你主线程没有 join,主线程运行完就退出了,然后就出问题了。
其次,imgurl 并没有完全被锁保护起来,for 循环里对 imgurl 的读是在锁外面的,会导致竞态。
python的多线程并不能真正的加快速度吧。 建议你用多进程(楼上的)或者gevent。爬虫网络下载是io密集型的。 了解一下gevent,速度快到飞起来。
gcondition.wait
这个操作是需要gcondition.notify
来唤醒的。
再来看你这个场景:
wait
的时候挂起来了,可这个时候geturl
往imgurl
里面又塞了很多url,然后saveimg
收到通知,继续执行。
请问:这个时候的 i
是个啥?
请输入代码
#! /usr/bin/python
import re
import urllib
import Queue
import threading
import os
import threadpool
#get the source code of a website
def getHtml(url):
print 'Getting html source code...'
page =urllib.urlopen(url)
#page = urllib.open(url)
html=page.read()
return html
def callfun(webaddr):
getname=webaddr.split('/')
urllib.urlretrieve(webaddr,'%s.jpg' % getname[-1])
def getdata(url,rule):
print 'Getting all address of images...'
imReg=re.compile(rule)
imList=re.findall(imReg,url)
return imList
def print_result(request,result):
print "the result is %s"%(request.requestID)
##main
htmlAddr="http://tieba.baidu.com/p/2510089409"
rule=r'src=\"(\S+\.jpg)\" pic_ext'
html=getHtml(htmlAddr)
data=getdata(html,rule)
pool=threadpool.ThreadPool(5)
requests=threadpool.makeRequests(callfun,data,print_result)
for req in requests:
pool.putRequest(req)
pool.wait()
你的方法我没用过, 不做置评. 我一般是这样解决的:
#!/usr/bin/env python
from multiprocessing.dummy import Pool, cpu_count
def get_url():
img_url = ["i am a img url list"]
return img_url
def save_img(url):
"""do some saving"""
pass
def main():
img_urls = get_url()
pool = Pool(cpu_count())
pool.map(save_img, img_urls)
pool.close()
pool.join()
if __name__ == "__main__":
main()