• 学习进度12


    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()

    多线程下载图片

  • 相关阅读:
    Thinkpad L440 无线驱动突然无法使用,无法搜索到无线上网
    如何判断服务器是物理机还是虚拟机
    生成Oracle的AWR报告
    Oracle数据库自带表空间
    Oracle数据库用户锁定原因以及处理方式(ORA-28000)
    Nginx反向代理和负载均衡
    Linux上Tomcat部署JavaWeb项目
    linux下memcached安装以及启动
    linux上安装activeMQ
    Windows下ActiveMQ下载、安装部署
  • 原文地址:https://www.cnblogs.com/gonT-iL-evoL-I/p/12312493.html
Copyright © 2020-2023  润新知