Python异步 -- aiohttp

发布时间 2023-06-12 11:36:42作者: 嘿十三

原文出处

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倍左右,速度非常之快。