Python异步 -- aiohttp
aiohttp
什么是 aiohttp?一个异步的 HTTP 客户端\服务端框架,基于 asyncio 的异步模块。可用于实现异步爬虫,更快于 requests 的同步爬虫。
安装
pip install aiohttp
aiohttp 和 requests对比
requests 版爬虫
requests 同步方式连续 30 次简单爬取 http://httpbin.org
网站
import requests from datetime import datetime def fetch(url): r = requests.get(url) print(r.text) start = datetime.now() for i in range(30): fetch('http://httpbin.org/get') end = datetime.now() print("requests版爬虫花费时间为:") print(end - start)
执行结果:
# 打印网站返回的内容 .... requests版爬虫花费时间为: 0:00:41.983785
从爬取结果可以看出,同步爬取30次网站将花费41秒左右的时间,耗时非常长。
aiohttp 版爬虫
使用 aiohttp 和 asyncio 异步方式简单爬取30次网站
import aiohttp import asyncio from datetime import datetime async def fetch(client): async with client.get('http://httpbin.org/get') as resp: assert resp.status == 200 return await resp.text() async def main(): async with aiohttp.ClientSession() as client: html = await fetch(client) print(html) loop = asyncio.get_event_loop() tasks = [] for i in range(30): task = loop.create_task(main()) tasks.append(task) start = datetime.now() loop.run_until_complete(main()) end = datetime.now() print("aiohttp版爬虫花费时间为:") print(end - start)
执行结果:
# 打印网站返回的内容 .... aiohttp版爬虫花费时间为: 0:00:00.639416
从爬取时间可以看出,aiohttp 异步爬取网站只用了0.6秒左右的时间,比 requests 同步方式快了70倍左右,速度非常之快。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律