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

 

posted @   嘿十三  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示