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性能
相关推荐
弹简特2 分钟前
【零基础学Python】08-Python面向对象之封装、多态和函数进阶
开发语言·python
人道领域5 分钟前
一篇文章解决Codex的安装,实操一遍过
java·开发语言·codex
thisiszdy11 分钟前
<C++> 智能指针
开发语言·c++
fox_lht13 分钟前
第十四章 一个输入和输出项目:构建一个命令行程序
开发语言·后端·rust
专注VB编程开发20年17 分钟前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
郑州光合科技余经理18 分钟前
海外版外卖系统:如何快速搭建国际化外卖平台
java·开发语言·前端·人工智能·小程序·系统架构·php
Cheng小攸20 分钟前
协议分析与分析工具(一)
开发语言·php
CC数学建模21 分钟前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
fox_lht23 分钟前
14.2.读文件
开发语言·后端·rust
codeejun23 分钟前
每日一Go-74、Go 云原生可观测性实战之OpenTelemetry 全链路采集:Trace + Metrics + Logs
开发语言·云原生·golang