asyncio.run()不可在已有事件循环中调用;Jupyter中应await或手动管理循环;FastAPI依赖中直接await;aiohttp.ClientSession须复用;gather适合批量请求,create_task适合精细控制;禁用requests+run_in_executor伪并发。

asyncio.run() 不能在已运行的事件循环中调用
直接在 Jupyter、Django shell 或某些 Web 框架(如 FastAPI 的依赖函数)里写 asyncio.run(main()),会报 RuntimeError: asyncio.run() cannot be called from a running event loop。这不是代码写错了,而是环境限制。
正确做法取决于上下文:
- 在普通 .py 脚本中:放心用
asyncio.run(),它是推荐入口 - 在 Jupyter 中:改用
await main()(确保单元格是 async 模式),或手动管理循环:asyncio.get_event_loop().run_until_complete(main()) - 在 FastAPI 依赖或中间件里:不要启动新 loop,直接
await即可 —— 框架已托管事件循环
aiohttp.ClientSession 必须复用,不能每次请求都新建
常见错误是把 aiohttp.ClientSession() 写在异步函数内部,导致每次请求都新建 session,不仅慢,还会快速耗尽本地端口(OSError: [Errno 24] Too many open files)。
正确结构是让 session 生命周期与并发任务对齐:
立即学习“Python免费学习笔记(深入)”;
- 在顶层
async def main()中创建一次session,传给子任务,或用async with包裹整个任务块 - 避免在循环内写
async with aiohttp.ClientSession() as session:—— 这等于为每个请求建一个 session - 如果需要设置超时、headers、cookie 等,都在 session 初始化时统一配置,而不是每次
session.get(url)时重复传参
示例片段:
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
async def fetch(session, url):
async with session.get(url) as resp:
return await resp.text()
<p>async def main():
timeout = aiohttp.ClientTimeout(total=10)
connector = aiohttp.TCPConnector(limit=100) # 控制并发连接数
async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
asyncio.gather() vs asyncio.create_task():选哪个取决于错误处理需求
asyncio.gather() 默认“全成功才返回”,任一协程抛异常,整个调用就中断(除非加 return_exceptions=True);而 create_task() 更灵活,适合需要单独监控、取消或按需 await 的场景。
实际选型建议:
- 批量发请求、不关心单个失败细节 → 用
gather(..., return_exceptions=True),之后用isinstance(r, Exception)过滤错误 - 要对某个请求做超时控制(比如只等 3 秒)、或失败后重试 2 次、或根据响应内容动态启停其他请求 → 改用
asyncio.create_task()+asyncio.wait_for()组合 - 别混用:不要在
gather()里塞create_task()返回的对象再 await —— 容易引发Task was destroyed but it is pending!
requests 不支持 async,硬套 asyncio.run_in_executor 只是伪并发
有人试图用 loop.run_in_executor(None, requests.get, url) 把同步库“塞进” asyncio,这确实不阻塞 event loop,但本质是开线程池,受 GIL 和系统线程数限制,无法真正压测出高并发能力,且内存和上下文切换开销远高于原生 async client。
真实高并发网络请求必须用原生异步 HTTP 库:
- 首选
aiohttp(功能全、可控性强、支持连接池) - 轻量场景可用
httpx.AsyncClient(API 更接近 requests,支持 HTTP/2) - 绝对不要用
urllib.request或requests配run_in_executor来“假装 async”
连接池参数(如 TCPConnector(limit=50))比并发数更重要 —— 它决定底层 socket 复用效率,直接影响 QPS 上限。
实际压测时,limit 设太高可能触发目标服务限流或本地端口耗尽,设太低又浪费并发能力。这个值需要结合目标域名的响应时间、超时设置、以及你机器的 ulimit -n 综合调整,不是越大越好。

















