关于反反爬虫技术:对限制连续请求时间的处理

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

下面利用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')

有关requests_cache的更多用法,参考下面requests_cache说明

爬虫相关库

1. 爬虫常用的测试网站:httpbin.org

httpbin.org 这个网站能测试 HTTP 请求和响应的各种信息,比如 cookie、ip、headers 和登录验证等,且支持 GET、POST 等多种方法,对 web 开发和测试很有帮助。它用 Python + Flask 编写,是一个开源项目。

官方网站:http://httpbin.org/ 

开源地址:https://github.com/Runscope/httpbin

2. requests-cache

requests-cache,是 requests 库的一个扩展包,利用它可以非常方便地实现请求的缓存,直接得到对应的爬取结果。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值