Requests什么的通通爬不了的Python超强反爬虫方案!


Posted in Python onMay 20, 2021

一、前言

一个非常强的反爬虫方案 —— 禁用所有 HTTP 1.x 的请求!

现在很多爬虫库其实对 HTTP/2.0 支持得不好,比如大名鼎鼎的 Python 库 —— requests,到现在为止还只支持 HTTP/1.1,啥时候支持 HTTP/2.0 还不知道。

Scrapy 框架最新版本 2.5.0(2021.04.06 发布)加入了对 HTTP/2.0 的支持,但是官网明确提示,现在是实验性的功能,不推荐用到生产环境,原文如下:

HTTP/2 support in Scrapy is experimental, and not yet recommended for production environments. Future Scrapy versions may introduce related changes without a deprecation period or warning.

插一句,Scrapy 中怎么支持 HTTP/2.0 呢?在 settings.py 里面换一下 Download Handlers 即可:

DOWNLOAD_HANDLERS = {
    'https': 'scrapy.core.downloader.handlers.http2.H2DownloadHandler',
}

当前 Scrapy 的 HTTP/2.0 实现的已知限制包括:

  • 不支持 HTTP/2.0 明文(h2c),因为没有主流浏览器支持未加密的 HTTP/2.0。
  • 没有用于指定最大帧大小大于默认值 16384 的设置,发送更大帧的服务器的连接将失败。
  • 不支持服务器推送。
  • 不支持bytes_received和 headers_received信号。

关于其他的一些库,也不必多说了,对 HTTP/2.0 的支持也不好,目前对 HTTP/2.0 支持得还可以的有 hyper 和 httpx,后者更加简单易用一些。

二、反爬虫

所以,你想到反爬虫方案了吗?

如果我们禁用所有的 HTTP/1.x 的请求,是不是能通杀掉一大半爬虫?requests 没法用了,Scrapy 除非升级到最新版本才能勉强用个实验性版本,其他的语言也不用多说,也会杀一大部分。

而浏览器对 HTTP/2.0 的支持现在已经很好了,所以不会影响用户浏览网页的体验。

三、措施

那就让我们来吧!

这个怎么做呢?其实很简单,在 Nginx 里面配置一下就好了,主要就是加这么个判断就行了:

if ($server_protocol !~* "HTTP/2.0") {
  return 444;
}

就是这么简单,这里 $server_protocol 就是传输协议,其结果目前有三个:HTTP/1.0HTTP/1.1 和 HTTP/2.0,另外判断条件我们使用了 !~* ,意思就是不等于,这里的判断条件就是,如果不是 HTTP/2.0,那就直接返回 444 状态码,444 一般代表 CONNECTION CLOSED WITHOUT RESPONSE,就是不返回任何结果关闭连接。

我的服务是在 Kubernetes 里面运行的,所以要加这个配置还得改下 Nginx Ingress 的配置,不过还好 https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/ 预留了一个配置叫做 nginx.ingress.kubernetes.io/server-snippet,利用它我们可以自定义 Nginx 的判定逻辑。

官方用法如下:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
        set $agentflag 0;
        if ($http_user_agent ~* "(Mobile)" ){
          set $agentflag 1;
        }
        if ( $agentflag = 1 ) {
          return 301 https://m.example.com;
        }

所以这里,我们只需要改成刚才的配置就好了:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
      if ($server_protocol !~* "HTTP/2.0") {
        return 444;
      }

大功告成!

配置完成了,示例网站是:https://spa16.scrape.center/

我们在浏览器中看下效果:

Requests什么的通通爬不了的Python超强反爬虫方案!

可以看到所有请求都是走的 HTTP/2.0,页面完全正常加载。

然而,我们使用 requests 来请求一下:

import requests
response = requests.get('https://spa16.scrape.center/')
print(response.text)

非常欢乐的报错:

Traceback (most recent call last):
  ...
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response
 
During handling of the above exception, another exception occurred:
 
Traceback (most recent call last):
  ...
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
requests.packages.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='spa16.scrape.center', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response')))
 
During handling of the above exception, another exception occurred:
 
Traceback (most recent call last):
 ...
requests.exceptions.ProxyError: HTTPSConnectionPool(host='spa16.scrape.center', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response')))

如果你用 requests,无论如何都不行的,因为它就不支持 HTTP/2.0。

那我们换一个支持 HTTP/2.0 的库呢?比如 httpx,安装方法如下:

pip3 install 'httpx[http2]'

注意,Python 版本需要在 3.6 及以上才能用 httpx。

安装好了之后测试下:

import httpx
client = httpx.Client(http2=True)
 
response = client.get('https://spa16.scrape.center/')
print(response.text)

结果如下:

<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><meta name=referrer content=no-referrer><link rel=icon href=/favicon.ico><title>Scrape | Book</title><link href=/css/chunk-50522e84.e4e1dae6.css rel=prefetch><link href=/css/chunk-f52d396c.4f574d24.css rel=prefetch><link href=/js/chunk-50522e84.6b3e24aa.js rel=prefetch><link href=/js/chunk-f52d396c.f8f41620.js rel=prefetch><link href=/css/app.ea9d802a.css rel=preload as=style><link href=/js/app.b93891e2.js rel=preload as=script><link href=/js/chunk-vendors.a02ff921.js rel=preload as=script><link href=/css/app.ea9d802a.css rel=stylesheet></head><body><noscript><strong>We're sorry but portal doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=app></div><script src=/js/chunk-vendors.a02ff921.js></script><script src=/js/app.b93891e2.js></script></body></html>

可以看到,HTML 就成功被我们获取到了!这就是 HTTP/2.0 的魔法!

我们如果把 http2 参数设置为 False 呢?

import httpx
client = httpx.Client(http2=False)
 
response = client.get('https://spa16.scrape.center/')
print(response.text)

一样很不幸:

Traceback (most recent call last):
 ...
    raise RemoteProtocolError(msg)
httpcore.RemoteProtocolError: Server disconnected without sending a response.
 
The above exception was the direct cause of the following exception:
  ...
    raise mapped_exc(message) from exc
httpx.RemoteProtocolError: Server disconnected without sending a response.

所以,这就印证了,只要 HTTP/1.x 通通没法治!可以给 requests 烧香了!

又一个无敌反爬虫诞生了!各大站长们,安排起来吧~

到此这篇关于Requests什么的通通爬不了的Python超强反爬虫方案!的文章就介绍到这了,更多相关Python反爬虫内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python函数式编程指南(四):生成器详解
Jun 24 Python
Python简单实现子网掩码转换的方法
Apr 13 Python
Python实现类似jQuery使用中的链式调用的示例
Jun 16 Python
详解python 注释、变量、类型
Aug 10 Python
500行Python代码打造刷脸考勤系统
Jun 03 Python
使用OpenCV实现仿射变换—缩放功能
Aug 29 Python
基于spring boot 日志(logback)报错的解决方式
Feb 20 Python
Python各种扩展名区别点整理
Feb 27 Python
Python自动化测试笔试面试题精选
Mar 12 Python
Python基于paramunittest模块实现excl参数化
Apr 26 Python
Python闭包装饰器使用方法汇总
Jun 29 Python
利用keras使用神经网络预测销量操作
Jul 07 Python
python使用glob检索文件的操作
python opencv通过按键采集图片源码
python 如何执行控制台命令与操作剪切板
教你怎么用Python生成九宫格照片
用 Python 元类的特性实现 ORM 框架
May 19 #Python
浅谈Python 中的复数问题
May 19 #Python
Python机器学习之基础概述
You might like
关于Iframe如何跨域访问Cookie和Session的解决方法
2013/04/15 PHP
PHP怎么实现网站保存快捷方式方便用户随时浏览
2013/08/15 PHP
php判断正常访问和外部访问的示例
2014/02/10 PHP
php实现对象克隆的方法
2015/06/20 PHP
PHP 中魔术常量的实例详解
2017/10/26 PHP
为数据添加append,remove功能
2006/10/03 Javascript
对联广告js flash激活
2006/10/19 Javascript
JavaScript获取页面上被选中文字的方法技巧
2015/03/13 Javascript
第三篇Bootstrap网格基础
2016/06/21 Javascript
jQuery 跨域访问解决原理案例详解
2016/07/09 Javascript
bootstrap网格系统使用方法解析
2017/01/13 Javascript
AngularJS路由实现页面跳转实例
2017/03/03 Javascript
node.js利用socket.io实现多人在线匹配联机五子棋
2018/05/31 Javascript
vee-validate vue 2.0自定义表单验证的实例
2018/08/28 Javascript
微信小程序实现张图片合成为一张并下载
2019/07/16 Javascript
Python中的模块和包概念介绍
2015/04/13 Python
Python实现单词拼写检查
2015/04/25 Python
Python编程生成随机用户名及密码的方法示例
2017/05/05 Python
Windows平台Python连接sqlite3数据库的方法分析
2017/07/12 Python
浅谈Python Opencv中gamma变换的使用详解
2018/04/02 Python
GitHub 热门:Python 算法大全,Star 超过 2 万
2019/04/29 Python
对Django中static(静态)文件详解以及{% static %}标签的使用方法
2019/07/28 Python
用Python批量把文件复制到另一个文件夹的实现方法
2019/08/16 Python
Pytorch之保存读取模型实例
2019/12/30 Python
pytorch实现建立自己的数据集(以mnist为例)
2020/01/18 Python
numpy矩阵数值太多不能全部显示的解决
2020/05/14 Python
HTML5计时器小例子
2013/10/15 HTML / CSS
html5使用canvas画空心圆与实心圆
2014/12/15 HTML / CSS
请写出 BOOL flag 与"零值"比较的 if 语句
2016/02/29 面试题
销售会计岗位职责
2014/03/15 职场文书
网络宣传方案
2014/03/15 职场文书
入党现实表现材料
2014/12/23 职场文书
2015年中学体育教师工作总结
2015/10/23 职场文书
python基于scrapy爬取京东笔记本电脑数据并进行简单处理和分析
2021/04/14 Python
JavaScript 中for/of,for/in 的详细介绍
2021/11/17 Javascript
码云(gitee)通过git自动同步到阿里云服务器
2022/12/24 Servers