如何大幅度提高requests的访问速度

发布时间:2022-01-14 21:42:20 作者:柒染
来源:亿速云 阅读:139

如何大幅度提高requests的访问速度,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

我做了一个垃圾信息过滤的 HTTP 接口。现在有一千万条消息需要经过这个接口进行垃圾检测。

一开始我的代码是这样的:

import requests
messages = ['第一条', '第二条', '第三条']
for message in messages:
   resp = requests.post(url, json={'msg': message}).json()
   if resp['trash']:
       print('是垃圾消息')
 

我们写一段代码来看看运行速度:

如何大幅度提高requests的访问速度  

访问一百次百度,竟然需要 20 秒。那我有一千万条信息,这个时间太长了。

有没有什么加速的办法呢?除了我们之前文章讲到的 多线程、aiohttp 或者干脆用 Scrapy 外,还可以让 requests 保持连接从而减少频繁进行 TCP 三次握手的时间消耗。

那么要如何让 requests 保持连接呢?实际上非常简单,使用Session对象即可。

修改后的代码:

import requests
import time

start = time.time()
session = requests.Session()
for _ in range(100):
   resp = session.get('https://baidu.com').content.decode()
end = time.time()
print(f'访问一百次网页,耗时:{end - start}')
 

运行效果如下图所示:

如何大幅度提高requests的访问速度  

性能得到了显著提升。访问 100 页只需要 5 秒钟。

在官方文档[1]中,requests 也说到了 Session对象能够保持连接:

  

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

”  
  

Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!

”  
    

看完上述内容,你们掌握如何大幅度提高requests的访问速度的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 织梦提高网页访问速度的方法
  2. 如何提高网站的打开速度?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

requests

上一篇:云计算中SOA指的是什么

下一篇:springboot整合quartz定时任务框架的方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》