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

  • Post author:
  • Post category:其他





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 —



版权声明:本文为weixin_46275180原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。