多线程爬虫(生产者消费者模式)

常规爬虫

# -*- coding:utf-8 -*-

import requests
from lxml import etree
from urllib import request
import os
import re

def parse_page(url):
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/70.0.3538.110 Safari/537.36",
        "Referer":"https://www.doutula.com/photo/list/"
    }
    r = requests.get(url,headers=headers)
    text = r.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) #分割后缀
        filename = alt + suffix[1].replace('!dta','')
        request.urlretrieve(img_url,'E:/python/Crawler/thread_demo/img/'+filename)
        print(filename+' 下载完成')



def main():
    for x in range(101):
        url = "https://www.doutula.com/photo/list/?page=%d" %x
        parse_page(url)
        print('第%d页'%(x))

if __name__ == '__main__':
    main()

多线程爬虫

# -*- coding:utf-8 -*-

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/70.0.3538.110 Safari/537.36",
        "Referer":"https://www.doutula.com/photo/list/"
    }
    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):
        r = requests.get(url,headers=self.headers)
        text = r.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) #分割后缀
            filename = alt + suffix[1].replace('!dta','')
            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,'E:/python/Crawler/thread_demo/img/'+filename)
            print(filename+' 下载完成')

def main():
    page_queue = Queue(100)
    img_queue = Queue(1000)
    for x in range(1,101):
        url = "https://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()
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页