在python并发请求中正确复用

为什么频繁创建会话会导致性能下降
频繁创建

import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
# 错误做法:在循环内部创建会话
urls = ["http://example.com", "http://example.org"]
for url in urls:
async with aiohttp.ClientSession() as session: # 每次循环都新建
result = await fetch(session, url)
print(result)
# 正确做法:外部创建一次,多次复用
async with aiohttp.ClientSession() as session: # 只创建一次
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
如何安全地管理会话的生命周期
安全管理async with)包裹整个并发任务块,或者在单例模式中维护一个长期运行的会话实例。如果选择后者,必须在应用程序关闭时显式调用
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import aiohttp
import asyncio
# 全局会话示例(需谨慎处理关闭逻辑)
session = None
async def init_session():
global session
connector = aiohttp.TCPConnector(limit=100)
session = aiohttp.ClientSession(connector=connector)
async def close_session():
global session
if session:
await session.close()
session = None
async def worker(url):
async with session.get(url) as resp:
return await resp.json()
async def main():
await init_session()
try:
tasks = [worker("http://api.example.com/data") for _ in range(50)]
await asyncio.gather(*tasks)
finally:
await close_session()
asyncio.run(main())
当并发量超过连接器限制时会发生什么
当并发请求数量超过
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










