前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >requests 扩展 | Requests-Cache(爬虫缓存)

requests 扩展 | Requests-Cache(爬虫缓存)

作者头像
数据STUDIO
发布2021-06-24 10:27:45
1.9K0
发布2021-06-24 10:27:45
举报
文章被收录于专栏:数据STUDIO

requests模块持久化缓存提供支持。在我们使用浏览器浏览网页时,经常会有大量的缓存,为你二次访问网站时更加快速地加载网页。同样地,当使用requests模块向一个URL发送重复请求时,也需要判断当前网络是否产生了缓存。此时Requests-Cache模块将会自动判断,若产生了缓存,则会读取数据作为响应内容。若没有缓存,则与第一次请求一样,获取服务器返回的响应内容。这样可以变相地躲避一些反爬机制。

代码语言:javascript
复制
>>> # 安装Requests-Cache模块
>>> pip install requests-cache
>>> # 检查模块是否安装成功
>>> import requests_cache
>>> requests_cache.__version__
'0.5.2'

install_cache()

Requests-Cache模块缓存应用,掌握一个install_cache()就够了。

代码语言:javascript
复制
requests_cache.install_cache(
    cache_name='cache',
    backend=None,
    expire_after=None,
    allowable_codes=(200,),
    allowable_methods=('GET',),
    filter_fn=<function <lambda> at 0x11c927f80>,
    session_factory=<class 'requests_cache.core.CachedSession'>,
    **backend_options,
)

一般情况下,不需要单独设置任何参数,使用默认参数即可,为了理解函数功能,一下介绍下各个参数的含义。 cache_name:缓存文件名称。 backend:设置缓存的存储机制,默认使用sqlite进行存储。 支持四种不同的存储机制,分别为memory、sqlite、mongoDB、redis。在设置存储机制为mongoDB、redis时需要提前安装对应的模块。pip install pymongo; pip install redies。

  • memory:以字典的形式将缓存存储在内存当中,程序运行完以后缓存将被销毁
  • sqlite:将缓存存储在sqlite数据库
  • mongoDB:将缓存存储在mongoDB数据库
  • redis:将缓存存储在redis

expire_after:设置缓存的有效时间,默认永久有效。 allowable_codes:设置状态码。 allowable_methods:设置请求方式,默认get,表示只有get请求才可以生成缓存。 session_factory:设置缓存执行的对象,需要实现CachedSession类。 **backend_options:如果缓存的存储方式为sqlit、mongo、redis数据库,该参数表示设置数据库的连接方式。


应用

代码语言:javascript
复制
>>> import requests_cache
>>> import requests
>>> requests_cache.install_cache() # 设置缓存
>>> requests_cache.clear() # 清空缓存
>>> url = 'http://httpbin.org/get'
>>> res = requests.get(url)
>>> print(f'cache exists: {res.from_cache}')
cache exists: False # 不存在缓存

>>> res = requests.get(url)
>>> print(f'exists cache: {res.from_cache}')
exists cache: True # 存在缓存

一般的反爬措施是在多次请求之间增加随机的间隔时间,即设置一定的延时。但如果请求后存在缓存,就可以省略设置延迟,这样一定程度地缩短了爬虫程序的耗时。

如下运用Requests-Cache模块定义钩子函数,合理判断是否使用延时操作。

代码语言:javascript
复制
import requests_cache
import time
requests_cache.install_cache()
requests_cache.clear()
def make_throttle_hook(timeout=0.1):
  def hook(response, *args, **kwargs):
       print(response.text)
      # 判断没有缓存时就添加延时
        if not getattr(response, 'from_cache', False):
            print(f'Wait {timeout} s!')
            time.sleep(timeout)
        else:
           print(f'exists cache: {response.from_cache}')
        return response
    return hook
if __name__ == '__main__':
   requests_cache.install_cache()
    requests_cache.clear()
    session = requests_cache.CachedSession() # 创建缓存会话
    session.hooks = {'response': make_throttle_hook(2)} # 配置钩子函数
    print('first requests'.center(50,'*'))
    session.get('http://httpbin.org/get')
    print('second requests'.center(50,'*'))
    session.get('http://httpbin.org/get')

运行结果如下:

代码语言:javascript
复制
******************first requests******************
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-5fd19b79-4df1d1e10743807f78ed5776"
  }, 
  "origin": "222.211.172.248", 
  "url": "http://httpbin.org/get"
}

Wait 2 s!
******************second requests******************
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-5fd19b79-4df1d1e10743807f78ed5776"
  }, 
  "origin": "222.211.172.248", 
  "url": "http://httpbin.org/get"
}

exists cache: True
<Response [200]>

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-12-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据STUDIO 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • install_cache()
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档