• python 爬虫系列09-异步斗图来一波


    斗图斗图,妈妈再也不怕我都不赢了

    import requests
    from lxml import etree
    from urllib import request
    import os
    import re
    from queue import Queue
    import threading
    
    class Procuder(threading.Thread):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'
        }
        def __init__(self,page_queue, img_queue, *args, **kwargs):
            super(Procuder, 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):
            reponse = requests.get(url, headers=self.headers)
            text = reponse.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')
                alt = img.get('alt')
                alt = re.sub(r'[?./"<>:?!,!*]','',alt)
                suffix = os.path.splitext(img_url)[1]
                filename = alt + suffix
                filename = re.sub(r'!dta', '', filename)
                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.img_queue.empty() and self.page_queue.empty():
                    break
                img_url, filename = self.img_queue.get()
                request.urlretrieve(img_url, 'image2/'+filename)
                print(filename+'   下载完成!!')
    
    def main():
        page_queue = Queue(100)
        img_queue = Queue(1000)
        for x in range(1, 200):
            url = 'http://www.doutula.com/photo/list/?page=%d' % x
            page_queue.put(url)
        for x in range(5):
            t = Procuder(page_queue, img_queue)
            t.start()
        for x in range(5):
            t = Consumer(page_queue, img_queue)
            t.start()
    if __name__ == '__main__':
        main()
  • 相关阅读:
    排序算法
    各种容器
    avl树
    zhenya moves from parents
    maven 相关
    Spring Cloud 子项目介绍
    WebStorm 中 dva 项目用 start 命令需要不断重启项目问题
    git常用命令
    SQL 的各种 join 用法
    程序员成长过程
  • 原文地址:https://www.cnblogs.com/kingle-study/p/9916230.html
Copyright © 2020-2023  润新知