Python requests及aiohttp速度对比代码实例

作者:陈严肃 时间:2023-11-22 14:40:37 

环境:centos7 python3.6

测试网址:www.bai.com

测试方式:抓取百度100次

结果:

aio: 10.702147483825684s
requests: 12.404678583145142s

异步框架的速度还是有显著提升的。

下面贡献代码:


import aiohttp
import time
import requests
import asyncio

def test_requests():
 """ 测试requessts请求百度100次时间 """

start = time.time()
 url = "https://www.baidu.com"
 for i in range(100):
   requests.get(url)
 end = time.time()
 print("requests:")
 print( end - start )

async def aio_download(url):
 """ aiohttp 下载 """

async with aiohttp.ClientSession() as session:
   await session.get(url)

async def test_aio():
 """ 测试aiohtpp请求百度100次时间 """
 url = "https://www.baidu.com"
 start = time.time()
 for i in range(100):
   await aio_download(url)
 end = time.time()
 print("aio: ")
 print( end - start )

if __name__ == "__main__":

loop = asyncio.get_event_loop()
 loop.run_until_complete(test_aio())

test_requests()

————————————————————————————————————————

-—————————————————————————————————————————

小贴士:

requests不要使用session进行反复抓取一个网站的测试,因为从第2次开始,读取的就是缓存了,无论抓取50次还是100次或是更多,总时间都是1s以内。

来源:https://www.cnblogs.com/chenyansu/p/9419296.html

标签:Python,requests,aiohttp
0
投稿

猜你喜欢

  • golang 如何用反射reflect操作结构体

    2024-05-08 10:22:45
  • 对内联文字的疑惑

    2008-04-18 12:19:00
  • MySQL中Order By多字段排序规则代码示例

    2024-01-22 01:10:35
  • Pycharm无法打开双击没反应的问题及解决方案

    2021-09-06 07:34:30
  • asp 使用正则表达式替换word中的标签,转为纯文本

    2011-02-28 10:49:00
  • Python socket模块ftp传输文件过程解析

    2021-04-17 02:22:59
  • vue实际运用之vuex持久化详解

    2024-05-09 15:15:50
  • PHP简单实现正则匹配省市区的方法

    2023-11-14 22:24:09
  • PHP开发之归档格式phar文件概念与用法详解【创建,使用,解包还原提取】

    2023-09-08 11:36:58
  • python超时重新请求解决方案

    2022-04-22 00:16:12
  • 浅谈mysql增加索引不生效的几种情况

    2024-01-25 20:34:43
  • MySQL权限分配

    2011-01-29 16:37:00
  • SQL Function 自定义函数详解

    2024-01-15 20:33:23
  • 元组列表字典(莫烦python基础)

    2022-03-23 09:15:58
  • 解读ASP.NET 5 & MVC6系列教程(6):Middleware详解

    2023-07-23 22:27:34
  • 数据挖掘之Apriori算法详解和Python实现代码分享

    2022-02-07 00:29:59
  • Windows和Linux下Python输出彩色文字的方法教程

    2021-04-15 11:15:41
  • js正则表达式验证密码强度【推荐】

    2024-04-29 13:39:30
  • 5个充满想象力的Web调色板

    2008-08-02 12:55:00
  • 浅析python 通⽤爬⾍和聚焦爬⾍

    2021-06-13 00:14:23
  • asp之家 网络编程 m.aspxhome.com