多线程生产者消费者模型爬虫

import queue

import requests
from bs4 import BeautifulSoup
import threading
import time
import random def craw(url):
r = requests.get(url=url)
return r.text def parse(html):
soup = BeautifulSoup(html, "html.parser")
links = soup.find_all("a", class_="post-time-title")
return [(link["href"], link.get_test()) for link in links] def do_craw(url_queue: queue.Queue, html_queue: queue.Queue):
while True:
url = url_queue.get()
html = craw(url)
html_queue.put(html)
print(threading.current_thread().name, url)
time.sleep(random.randint(1,2)) def do_parse(html_queue:queue.Queue, f_out):
while True:
html = html_queue.get()
results = parse(html)
for result in results:
f_out.write(str(result) + "\n")
print(threading.current_thread().name, html_queue.qsize())
time.sleep(1) if __name__ == '__main__':
url_queue = queue.Queue()
html_queue = queue.Queue()
for url in ["https://www.cnblogs.com/#p{}".format(i) for i in range(1, 25)]:
url_queue.put(url) for idx in range(3):
t = threading.Thread(target=do_craw, args=(url_queue, html_queue), name=f"craw-{idx}")
t.start() file = open("02.data.txt", "w")
for idx in range(2):
d = threading.Thread(target=do_parse, args=(html_queue, file), name=f"parse-{idx}")
d.start()

多线程池爬虫

from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
from bs4 import BeautifulSoup spider_url = ["https://www.cnblogs.com/#p{}".format(i) for i in range(1, 25)] def craw(url):
r = requests.get(url=url)
return r.text def parse(html):
soup = BeautifulSoup(html, "html.parser")
links = soup.find_all("a", class_="post-time-title")
return [(link["href"], link.get_test()) for link in links] # craw
with ThreadPoolExecutor() as pool:
htmls = pool.map(craw, spider_url)
htmls = list(zip(spider_url, htmls))
for k, v in htmls:
print(k, len(v)) with ThreadPoolExecutor() as pool:
futures = {}
for url, html in htmls:
future = pool.submit(parse, html)
futures[future] = url # for k, v in futures.items():
# print(v, k.result())
for future in as_completed(futures):
print(futures[future], future.result())

协程

import asyncio
import aiohttp spider_url = ["https://www.cnblogs.com/taozhengquan/p/14966535.html"]*50 # 信号量控制爬虫数量
semaphore = asyncio.Semaphore(10) async def async_craw(url):
async with semaphore:
print("craw url:", url)
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
result = await resp.text()
print(url, len(result)) loop = asyncio.get_event_loop()
tasks = [
loop.create_task(async_craw(item)) for item in spider_url
]
loop.run_until_complete(asyncio.wait(tasks))

Python 多线程、线程池、协程 爬虫的更多相关文章

  1. python之路32 网络并发线程方法 线程池 协程

    多进程实现TCP服务端并发 服务端: import socket from multiprocessing import Process def get_server(): server = sock ...

  2. python进程.线程和协程的总结

    I.进程: II.多线程threading总结 threading用于提供线程相关的操作,线程是应用系统中工作的最小单位(cpu调用的最小单位). Python当前版本的多线程没有实现优先级,线程组, ...

  3. 互斥锁 线程理论 GIL全局解释器锁 死锁现象 信号量 event事件 进程池与线程池 协程实现并发

    目录 互斥锁 multiprocessing Lock类 锁的种类 线程理论 进程和线程对比 开线程的两种方式(类似进程) 方式1 使用Thread()创建线程对象 方式2 重写Thread类run方 ...

  4. 11.python之线程,协程,进程,

    一,进程与线程 1.什么是线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行 ...

  5. 05网络并发 ( GIL+进程池与线程池+协程+IO模型 )

    目录 05 网络并发 05 网络并发

  6. python全栈开发 * 线程队列 线程池 协程 * 180731

    一.线程队列 队列:1.Queue 先进先出 自带锁 数据安全 from queue import Queue from multiprocessing import Queue (IPC队列)2.L ...

  7. python并发编程-进程池线程池-协程-I/O模型-04

    目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...

  8. python 线程(其他方法,队列,线程池,协程 greenlet模块 gevent模块)

    1.线程的其他方法 from threading import Thread,current_thread import time import threading def f1(n): time.s ...

  9. python简单线程和协程学习

    python中对线程的支持的确不够,不过据说python有足够完备的异步网络框架模块,希望日后能学习到,这里就简单的对python中的线程做个总结 threading库可用来在单独的线程中执行任意的p ...

  10. Day037--Python--线程的其他方法,GIL, 线程事件,队列,线程池,协程

    1. 线程的一些其他方法 threading.current_thread()  # 线程对象 threading.current_thread().getName()  # 线程名称 threadi ...

随机推荐

  1. HMS Core助力同程旅行,打造更贴心的用户出行体验

    作为中国在线旅行行业的创新者,同程旅行聚焦年轻.时尚.个性的消费群体,致力于为用户提供更便捷.聪明.安全的出行服务.近年来,同程旅行通过人工智能等创新科技的应用将平台原本的交易撮合角色转变为" ...

  2. Qt使用https协议发送带参数的post请求

    背景: 现在公司项目需要做一个检测更新的功能,通过访问后台接口,判断是否需要更新. 后台接口是 https 协议的,接口需要post请求,需要带参数,来判断是哪个软件需要做检测更新的操作. 客户端软件 ...

  3. 国产开源数据库OpenGauss的安装运行

    步骤一:OpenGauss 的安装 环境 OS:openEuler 20.03 64bit with ARM 架构:arm64 部署:单机 安装过程 1.环境配置 安装依赖包: yum install ...

  4. 第十五篇:JavaScript 之 Dom操作

    一.后台管理页面布局 主站布局 <div class="pg-header"></div> <div style="width:980px; ...

  5. JackSon反序列化通杀

    前言 Springboot一般都会自带JackSon这个依赖包,JackSon跟Fastjson有相同的功效 简单复现 package com.example.jakeson.demo; import ...

  6. Centos8防火墙配置、端口、进程管理

    Centos8停用.启用.查看当前启用的端口 firewall-cmd --zone=public --add-port=5672/tcp --permanent # 开放5672端口 firewal ...

  7. UML 哲学之道——启航篇[一]

    前言 简单去介绍一下uml的哲学之道也是自我整理之道. 正文 什么是uml,全程是统一建模语言(unified modeling language),简单的说就是用图形来表示文档. 是描述构造和文档化 ...

  8. 为什么序列化要实现Serializable接口

    为什么实现了Serializable接口就会序列化? 实现了Java中的Serializable接口的类会被称为可序列化的,这意味着它们的实例可以被序列化为字节流,以便于在网络上传输.保存到文件中或者 ...

  9. Oracle nullif函数使用

    nullif函数使用 简单来说,就是表达式1的值和表达式2的值进行对比 可以使用''字符 select nullif('','1111') from dual 输出为空 不可以使用null字符 sel ...

  10. 力扣744(java&python)- 寻找比目标字母大的最小字母(简单)

    题目: 给你一个排序后的字符列表 letters ,列表中只包含小写英文字母.另给出一个目标字母 target,请你寻找在这一有序列表里比目标字母大的最小字母. 在比较时,字母是依序循环出现的.举个例 ...