import requests from lxml import html from urllib import request import os import re import threading from queue import Queue etree = html.etree class P(threading.Thread): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400' } def __init__(self, page_queue, img_queue, *args, **kwargs): super(P, 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): resp = requests.get(url, headers=self.headers) text = resp.text html = etree.HTML(text) imgs = html.xpath("//div[@class='page-content text-center']//img[@class!='gif']") for img in imgs: # 获取图片属性 img_url = img.get('data-original') img_name = img.get('alt') img_name = re.sub(r'[??.,。!!*]', '', img_name) # 分隔 提取文件后缀 suffix = os.path.splitext(img_url)[1] # 组成文件名 filename = img_name + suffix print(filename) self.img_queue.put((img_url, filename)) class C(threading.Thread): def __init__(self, page_queue, img_queue, *args, **kwargs): super(C, self).__init__(*args, **kwargs) self.page_queue = page_queue self.img_queue = img_queue def run(self): while True: if self.img_queue.empty() and self.page_queue.empty(): break img_url,filename = self.img_queue.get() # 下载到本地 request.urlretrieve(img_url, 'imgs/' + filename) def main(): page_queue = Queue(100) img_queue = Queue(500) for x in range(1, 100): url = 'http://www.doutula.com/photo/list/?page=%d' % x page_queue.put(url) for x in range(5): t = P(page_queue, img_queue) t.start() for x in range(5): t = C(page_queue, img_queue) t.start() if __name__ == '__main__': main()
多线程下载图片