爬虫入门(十)线程池and协程池爬虫

线程池使用方法介绍

1.实例化线程池对象

 from multiprocessing.dummy import Pool
 pool = Pool(process=5) #默认大小是cup的个数

2.把从发送请求,提取数据,到保存合并成一个函数,交给线程池异步执行,使用方法pool.apply_async(func)

 def exetute_requests_item_save(self):
     url = self.queue.get()
     html_str = self.parse_url(url)
     content_list = self.get_content_list(html_str)
     self.save_content_list(content_list)
     self.total_response_num +=1

 pool.apply_async(self.exetute_requests_item_save)

3.添加回调函数
通过apply_async的方法能够让函数异步执行,但是只能够执行一次
为了让其能够被反复执行,通过添加回调函数的方式能够让_callback 递归的调用自己,同时需要指定递归退出的条件

def _callback(self,temp):
     if self.is_running:
          pool.apply_async(self.exetute_requests_item_save,callback=self._callback)
 pool.apply_async(self.exetute_requests_item_save,callback=self._callback)

4.确定程序结束的条件 程序在获取的响应和url数量相同的时候可以结束

 while True: #防止主线程结束
     time.sleep(0.0001)  #避免cpu空转,浪费资源
     if self.total_response_num>=self.total_requests_num:
         self.is_running= False
         break
 self.pool.close() #关闭线程池,防止新的线程开启
# self.pool.join() #等待所有的子线程结束

练习

1.使用线程池实现爬虫的具体实现

# coding=utf-8
import requests
from lxml import etree
import time
from queue import Queue
from multiprocessing.dummy import Pool

class QiuBai:
    def __init__(self):
        self.temp_url = "http://www.qiushibaike.com/8hr/page/{}"
        self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}
        self.queue = Queue()
        self.pool= Pool(5)
        self.is_running = True
        self.total_request_num = 0
        self.total_response_num =0
        self.proxies = {"http":"http://58.247.179.94:8060"}


    def get_url_list(self):
        for i in range(1,14):
            self.queue.put(self.temp_url.format(i))
            self.total_request_num += 1

    def parse_url(self,url):
        # response = requests.get(url,headers=self.headers,proxies=self.proxies)
        response = requests.get(url,headers=self.headers)
        print(response)
        return response.content.decode()

    def get_content_list(self,html_str):#提取数据
        html = etree.HTML(html_str)
        div_list = html.xpath("//div[@id='content-left']/div")
        content_list = []
        for div in div_list:
            item = {}
            item["user_name"] = div.xpath(".//h2/text()")[0].strip()
            item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
            content_list.append(item)
        return content_list

    def save_content_list(self,content_list): #保存
        for content in content_list:
            # print(content)
            pass

    def _execete_request_content_save(self):  #进行一次url地址的请求,提取,保存
        url = self.queue.get()
        html_str = self.parse_url(url)
        #3. 提取数据
        content_list = self.get_content_list(html_str)
        #4. 保存
        self.save_content_list(content_list)
        self.total_response_num +=1

    def _callback(self,temp):
        if self.is_running:
            self.pool.apply_async(self._execete_request_content_save,callback=self._callback)


    def run(self):#实现做主要逻辑
        #1. 准备url列表
        self.get_url_list()
        for i in range(3): #设置并发数为3
            self.pool.apply_async(self._execete_request_content_save,callback=self._callback)

        while True:
            time.sleep(0.0001)
            if self.total_response_num>= self.total_request_num:
                self.is_running = False
                break


if __name__ == '__main__':
    t1 = time.time()
    qiubai = QiuBai()
    qiubai.run()
    print("total cost:",time.time()-t1)

2.使用协程池实现爬虫的具体实现

# coding=utf-8
import gevent.monkey
gevent.monkey.patch_all()

from gevent.pool import  Pool
import requests
from lxml import etree
import time
from queue import Queue
# from multiprocessing.dummy import Pool

class QiuBai:
    def __init__(self):
        self.temp_url = "http://www.qiushibaike.com/8hr/page/{}"
        self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}
        self.queue = Queue()
        self.pool= Pool(5)
        self.is_running = True
        self.total_request_num = 0
        self.total_response_num =0
        self.proxies = {"http":"http://58.247.179.94:8060"}


    def get_url_list(self):
        for i in range(1,14):
            self.queue.put(self.temp_url.format(i))
            self.total_request_num += 1

    def parse_url(self,url):
        # response = requests.get(url,headers=self.headers,proxies=self.proxies)
        response = requests.get(url,headers=self.headers)
        print(response)
        return response.content.decode()

    def get_content_list(self,html_str):#提取数据
        html = etree.HTML(html_str)
        div_list = html.xpath("//div[@id='content-left']/div")
        content_list = []
        for div in div_list:
            item = {}
            item["user_name"] = div.xpath(".//h2/text()")[0].strip()
            item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
            content_list.append(item)
        return content_list

    def save_content_list(self,content_list): #保存
        for content in content_list:
            # print(content)
            pass

    def _execete_request_content_save(self):  #进行一次url地址的请求,提取,保存
        url = self.queue.get()
        html_str = self.parse_url(url)
        #3. 提取数据
        content_list = self.get_content_list(html_str)
        #4. 保存
        self.save_content_list(content_list)
        self.total_response_num +=1

    def _callback(self,temp):
        if self.is_running:
            self.pool.apply_async(self._execete_request_content_save,callback=self._callback)



    def run(self):#实现做主要逻辑
        #1. 准备url列表
        self.get_url_list()
        for i in range(3): #设置并发数为3
            self.pool.apply_async(self._execete_request_content_save,callback=self._callback)

        while True:
            time.sleep(0.0001)
            if self.total_response_num>= self.total_request_num:
                self.is_running = False
                break


if __name__ == '__main__':
    t1 = time.time()
    qiubai = QiuBai()
    qiubai.run()
    print("total cost:",time.time()-t1)

你可能感兴趣的:(爬虫入门(十)线程池and协程池爬虫)