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性能
相关推荐
组合缺一3 小时前
用 ChatModel 构建 LLM 驱动的 Java 应用
java·开发语言·ai·llm·solon·rag
许彰午3 小时前
73_Python爬虫Scrapy框架入门
爬虫·python·scrapy
@realXuan3 小时前
人工智能AI编程 Agent 入门系列教程之 Claude Code 是什么
人工智能·python·ai编程
孤狼warrior3 小时前
从冒泡到传送带流水线:一个3D沉浸式算法靶场,让思想的伟力改变世界
python·算法·typescript
零点零一3 小时前
QT 5升级到 Qt 6 使用 Clazy 检查将 C++ 应用程序移植到 Qt 6
开发语言·c++·qt
搬砖柯3 小时前
系列11-测试平台 MCP Server 实践:用 Kimi Code 自然语言查项目、跑 API 回归
人工智能·python·ai·开源·自动化
向阳是我3 小时前
在 Mac(M2)上用 faster-whisper 实现高精度中文语音转文字
python·macos·ai·whisper·语音识别
caimouse3 小时前
reactos 测试安装32位微信失败的日志
开发语言·微信
山海云端有限公司3 小时前
企业工商信息查询API实战:从认证到数据解析全流程
python·api·数据解析·企业信息查询·聚合api·第三方集成
深蓝电商API3 小时前
模拟器批量操控:雷电/夜神 + ADB集群方案
数据仓库·爬虫·adb