Python 多线程、线程池、协程 爬虫
多线程生产者消费者模型爬虫
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 多线程、线程池、协程 爬虫的更多相关文章
- python之路32 网络并发线程方法 线程池 协程
多进程实现TCP服务端并发 服务端: import socket from multiprocessing import Process def get_server(): server = sock ...
- python进程.线程和协程的总结
I.进程: II.多线程threading总结 threading用于提供线程相关的操作,线程是应用系统中工作的最小单位(cpu调用的最小单位). Python当前版本的多线程没有实现优先级,线程组, ...
- 互斥锁 线程理论 GIL全局解释器锁 死锁现象 信号量 event事件 进程池与线程池 协程实现并发
目录 互斥锁 multiprocessing Lock类 锁的种类 线程理论 进程和线程对比 开线程的两种方式(类似进程) 方式1 使用Thread()创建线程对象 方式2 重写Thread类run方 ...
- 11.python之线程,协程,进程,
一,进程与线程 1.什么是线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行 ...
- 05网络并发 ( GIL+进程池与线程池+协程+IO模型 )
目录 05 网络并发 05 网络并发
- python全栈开发 * 线程队列 线程池 协程 * 180731
一.线程队列 队列:1.Queue 先进先出 自带锁 数据安全 from queue import Queue from multiprocessing import Queue (IPC队列)2.L ...
- python并发编程-进程池线程池-协程-I/O模型-04
目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...
- python 线程(其他方法,队列,线程池,协程 greenlet模块 gevent模块)
1.线程的其他方法 from threading import Thread,current_thread import time import threading def f1(n): time.s ...
- python简单线程和协程学习
python中对线程的支持的确不够,不过据说python有足够完备的异步网络框架模块,希望日后能学习到,这里就简单的对python中的线程做个总结 threading库可用来在单独的线程中执行任意的p ...
- Day037--Python--线程的其他方法,GIL, 线程事件,队列,线程池,协程
1. 线程的一些其他方法 threading.current_thread() # 线程对象 threading.current_thread().getName() # 线程名称 threadi ...
随机推荐
- Native Drawing开发指导,实现HarmonyOS基本图形和字体的绘制
场景介绍 Native Drawing模块提供了一系列的接口用于基本图形和字体的绘制.常见的应用场景举例: ● 2D图形绘制. ● 文本绘制. 接口说明 接口名 描述 OH_Drawing_Bit ...
- 动态规划(五)——坐标dp
传纸条 题目描述 小渊和小轩是好朋友也是同班同学,他们在一起总有谈不完的话题.一次素质拓展活动中,班上同学安排做成一个m行n列的矩阵, 而小渊和小轩被安排在矩阵对角线的两端,因此,他们就无法直接交谈了 ...
- Mysql安装和远程登录--Centos7
在Centos7中使用的包管理工具是yum,当然使用包管理工具安装也是最方便的. 本文操作内容需要在root用户下,否则有些步骤无法成功执行. 系统环境信息展示 安装 MySQL 提供的 RPM wg ...
- 架构设计|基于 raft-listener 实现实时同步的主备集群
背景以及需求 线上业务对数据库可用性可靠性要求较高,要求需要有双 AZ 的主备容灾机制. 主备集群要求数据和 schema 信息实时同步,数据同步平均时延要求在 1s 之内,p99 要求在 2s 之内 ...
- Java Agent 踩坑之 appendToSystemClassLoaderSearch 问题
简介: 从 Java Agent 报错开始,到 JVM 原理,到 glibc 线程安全,再到 pthread tls,逐步探究 Java Agent 诡异报错. 作者:鲁严波 从 Java Age ...
- 图像检索在高德地图POI数据生产中的应用
简介: 高德通过自有海量的图像源,来保证现实世界的每一个新增的POI及时制作成数据.在较短时间间隔内(小于月度),同一个地方的POI 的变化量是很低的. 作者 | 灵笼.怀迩 来源 | 阿里技术 ...
- 庖丁解牛-图解MySQL 8.0优化器查询解析篇
简介: SQL优化器本质上是一种高度抽象化的数据接口的实现,经过该设计,客户可以使用更通用且易于理解的SQL语言,对数据进行操作和处理,而不需要关注和抽象自己的数据接口,极大地解放了客户的应用程序. ...
- [FE] 被动检测 iframe 加载 src 成功失败的一种思路和方式 (Vue)
思路:设置定时器一个,n 秒后设置 404 或其它,此时给 iframe 的 onload 事件设置回调函数,加载完成则取消定时器. 示例: data () { return { handler: n ...
- [FAQ] Error: com.mysql.jdbc.Driver not loaded. :jdbc_driver_library
以上问题出现在 logstash.conf 未配置好 MySQL 的 JDBC 驱动时导致的错误提示. 首先,下载好 MySQL JDBC 驱动库,可以放到 logstash.conf 所在当前目录或 ...
- NopCommerce支持多种类型的数据库
本文章的内容是根据本人阅读NopCommerce源码的理解,如有不对的地方请指正,谢谢. 阅读目录 1.类结构关系图 2.分析 3.NopCommerce应用 类结构关系图 分析 NopObjectC ...