python爬虫,多线程与生产者消费者模式

  • 使用队列完成生产者消费者模式
  • 使用类创建多线程提高爬虫速度
python 复制代码
'''
https://sc.chinaz.com/tupian/index.html
https://sc.chinaz.com/tupian/index_2.html
https://sc.chinaz.com/tupian/index_3.html
'''

from threading import Thread
from queue import Queue
import requests
from bs4 import BeautifulSoup
import os

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69',
}
class Put_Thread(Thread):
    def __init__(self, url_queue, img_queue):
        super().__init__()
        self.url_queue = url_queue
        self.img_queue = img_queue

    def run(self):
        while not self.url_queue.empty():
            url = self.url_queue.get()
            self.fetch_url(url)

    def fetch_url(self, url):
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'
        soup = BeautifulSoup(response.text, 'lxml')
        data_list = soup.find_all('img', class_='lazy')
        for i in data_list:
            title = i.get('alt')
            href = 'https:' + i.get('data-original').replace('_s', '')
            self.img_queue.put((title, href))

class Get_Thread(Thread):
    def __init__(self, img_queue):
        super().__init__()
        self.img_queue = img_queue

    def run(self):
        while True:
            try:
                img_data = self.img_queue.get(timeout=3)
            except:
                break
            else:
                title, href = img_data
                if not os.path.exists('./image'):
                    os.mkdir('./image')
                with open('./image/' + title + '.jpg', 'wb') as f:
                    resp = requests.get(href, headers=headers).content
                    f.write(resp)
                print(title, '保存成功!')

def main():
    '''存放url'''
    url_queue = Queue()
    '''存放图片的地址和名称'''
    img_queue = Queue()

    url_queue.put('https://sc.chinaz.com/tupian/index.html')
    for i in range(1,11):
        url = 'https://sc.chinaz.com/tupian/index_{}.html'.format(i)
        url_queue.put(url)

    for i in range(41):
        t1 = Put_Thread(url_queue, img_queue)
        t1.start()
        t2 = Get_Thread(img_queue)
        t2.start()

if __name__ == '__main__':
    main()
    print('\n************主线程已结束************\n')
  • 通过队列可以让线程之间进行通信
  • 创建继承Thread的类创建线程,run()会在线程start时执行
  • 吃cpu性能
相关推荐
程序员阿龙7 分钟前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理
ZHOU_WUYI13 分钟前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
黑客老李21 分钟前
JavaSec | SpringAOP 链学习分析
java·运维·服务器·开发语言·学习·apache·memcached
开开心心就好30 分钟前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
且慢.58931 分钟前
Python_day47
python·深度学习·计算机视觉
特立独行的猫a35 分钟前
Nuxt.js 中的路由配置详解
开发语言·前端·javascript·路由·nuxt·nuxtjs
佩奇的技术笔记39 分钟前
Python入门手册:异常处理
python
勤奋的知更鸟1 小时前
Java编程之原型模式
java·开发语言·原型模式
大写-凌祁1 小时前
论文阅读:HySCDG生成式数据处理流程
论文阅读·人工智能·笔记·python·机器学习
珂朵莉MM1 小时前
2021 RoboCom 世界机器人开发者大赛-高职组(初赛)解题报告 | 珂学家
java·开发语言·人工智能·算法·职场和发展·机器人