当前位置: 首页 > news >正文

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 osheaders = {'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_queueself.img_queue = img_queuedef 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_queuedef run(self):while True:try:img_data = self.img_queue.get(timeout=3)except:breakelse:title, href = img_dataif not os.path.exists('./image'):os.mkdir('./image')with open('./image/' + title + '.jpg', 'wb') as f:resp = requests.get(href, headers=headers).contentf.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性能
http://www.lryc.cn/news/161718.html

相关文章:

  • WordPress 提示“此站点遇到了致命错误”的解决方法
  • Vue3,Typescript中引用组件路径无法找到模块报错
  • 科技成果鉴定之鉴定测试报告
  • NFTScan 浏览器正式版上线 2 周年!
  • 为什么要使用Token
  • 前端面试的话术集锦第 8 篇:高频考点(JS性能优化 性能优化琐碎事)
  • 【数据分析】Python:处理缺失值的常见方法
  • “批量随机字母命名文件,轻松管理你的文件库“
  • elasticsearch的数据聚合
  • 【网络编程·数据链路层】MAC帧/以太网协议/ARP协议/RARP协议
  • 算法:移除数组中的val的所有元素---双指针[2]
  • Python小知识 - Python爬虫进阶:如何克服反爬虫技术
  • SAP中的新旧事务码
  • day3_C++
  • 力扣题解(73. 矩阵置零),带注释
  • SpringMVC应用
  • 百度输入法全面升级,打造首个基于大模型的输入法原生应用
  • 如何解决GitHub 访问不了?小白教程
  • 龙芯指令集LoongArch——学习笔记(1)
  • ubuntu 20.04 docker安装emqx 最新版本或指定版本
  • 软件测试/测试开发丨学会与 AI 对话,高效提升学习效率
  • CEF内核和高级爬虫知识
  • 视频集中存储/云存储/磁盘阵列EasyCVR平台分组批量绑定/取消设备功能详解
  • 科技成果鉴定测试报告一般包含哪些测试内容?
  • IDEA中的“Deployment“ 将项目直接部署到服务器上
  • 密室逃脱小游戏
  • 【MyBatis】MyBatis项目结构的搭建
  • Vant组件库入门知识
  • Java字符串查找
  • 2023年7月京东投影仪行业品牌销售排行榜(京东大数据)