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

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

>>> # 安装Requests-Cache模块
>>> pip install requests-cache
>>> # 检查模块是否安装成功
>>> import requests_cache
>>> requests_cache.__version__
'0.5.2'

install_cache()

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

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数据库,该参数表示设置数据库的连接方式。


应用

>>> 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模块定义钩子函数,合理判断是否使用延时操作。

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')

运行结果如下:

******************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]>

推荐阅读

-- 数据STUDIO -- 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值