# qiutu 多线程 from lxml import etree import requests import os from urllib import request import threading from queue import Queue class Producer(threading.Thread): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" } def __init__(self,page_queue,img_queue,*args,**kwargs): super(Producer,self).__init__(*args,**kwargs) self.page_queue = page_queue self.img_queue = img_queue def run(self): while True: if self.page_queue.empty(): break url = self.page_queue.get() self.parse_page(url) def parse_page(self,url): response = requests.get(url=url,headers=self.headers).text tree = etree.HTML(response) pics = tree.xpath("//div[@class='main']//div[@class='thumb']//img") for pic in pics: # print(etree.tostring(pic)) img_url = pic.get('src') suffix = os.path.splitext(img_url)[1] img_url = "https:"+img_url img_name = pic.get('alt') filename = img_name + suffix self.img_queue.put((img_url,filename)) class Consumer(threading.Thread): def __init__(self,page_queue,img_queue,*args,**kwargs): super(Consumer,self).__init__(*args,**kwargs) self.page_queue = page_queue self.img_queue = img_queue def run(self): while True: if self.page_queue.empty() and self.img_queue.empty(): break img_url,filename = self.img_queue.get() request.urlretrieve(img_url,'qiubai_images/'+ filename) print(filename," 下载完毕") def main(): page_queue = Queue(100) img_queue = Queue(500) for x in range(1,11): url = "https://www.qiushibaike.com/pic/page/%d/?s=5195905"%x page_queue.put(url) for x in range(5): t = Producer(page_queue,img_queue) t.start() for x in range(5): t = Consumer(page_queue,img_queue) t.start() if __name__ == '__main__': main()