问题遇到的现象和发生背景
我通过requests和etree得到了一个图片的url列表,然后我把列表里的每一个值都放到我创建的队列里面去
然后我写一个download方法,这个download方法就负责下载图片,至于图片的url则从队列里面拿,队列可以拿一个少一个,每次拿最前面的就好了,然后图片的名字就是url的后36位字符
接下来我所需要的就是同时执行download函数多次
如果我一次一次来执行download函数的话,需要50次,差不多1min
但如果我一次能够执行5个download函数,那只需要10次,约等于10s
我就是不知道怎么同时去执行5个download函数
对于同一个函数,怎么将它同时执行多次?
运行结果及报错内容
这个代码没有报错,能跑,但什么结果也没有,一张图片都没爬回来
问题相关代码
from multiprocessing import Pool, Queue
import requests
from lxml import etree
class imgbinspider(object):
def get_html(self,url):
# Get the coding of the webpage↓
html = requests.get(url=url,headers=head).content.decode('utf-8')
res_xpath = etree.HTML(html)
# Put the url corresponding to the picture in the list↓
img_url_list = res_xpath.xpath(str('//img/@data-src'))
# Define a queue↓
url_queue = Queue()
# Put all the elements in the list into the queue↓
for i in range(len(img_url_list)):
url_queue.put(img_url_list[i])
self.name = 0
# Return a queue↓
return url_queue
def download(self):
imgurl = Url_Queue.get()
# Get pictures↓
image = requests.get(url=imgurl,headers=head).content
with open('E:\PythonFile\爬虫\实验品\多进程\爬虫\imgbin\图片\{}.jpg'.format(self.name),'wb')as f:
f.write(image)
self.name+=1
if __name__ == '__main__':
head={'user-agent': 'Mozilla/5.0'}
weburl = "https://imgbin.com/free-png/naruto"
spider=imgbinspider()
pool=Pool(5)
Url_Queue = spider.get_html(weburl)
i = 0
while i<11:
pool.apply_async(func=spider.download)
i+=1