超強(qiáng)反爬蟲方案!Requests 什么的通通爬不了 (留言送書)

想到這里,你可能就想到了一個(gè)非常強(qiáng)的反爬蟲方案 —— 禁用所有 HTTP 1.x 的請(qǐng)求!
現(xiàn)在很多爬蟲庫(kù)其實(shí)對(duì) HTTP/2.0 支持得不好,比如大名鼎鼎的 Python 庫(kù) —— requests,到現(xiàn)在為止還只支持 HTTP/1.1,啥時(shí)候支持 HTTP/2.0 還不知道。
Scrapy 框架最新版本 2.5.0(2021.04.06 發(fā)布)加入了對(duì) HTTP/2.0 的支持,但是官網(wǎng)明確提示,現(xiàn)在是實(shí)驗(yàn)性的功能,不推薦用到生產(chǎn)環(huán)境,原文如下:
“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',
}
當(dāng)前 Scrapy 的 HTTP/2.0 實(shí)現(xiàn)的已知限制包括:
不支持 HTTP/2.0 明文(h2c),因?yàn)闆]有主流瀏覽器支持未加密的 HTTP/2.0。 沒有用于指定最大幀大小大于默認(rèn)值 16384 的設(shè)置,發(fā)送更大幀的服務(wù)器的連接將失敗。 不支持服務(wù)器推送。 不支持 bytes_received和headers_received信號(hào)。
關(guān)于其他的一些庫(kù),也不必多說了,對(duì) HTTP/2.0 的支持也不好,目前對(duì) HTTP/2.0 支持得還可以的有 hyper 和 httpx,后者更加簡(jiǎn)單易用一些。
反爬蟲
所以,你想到反爬蟲方案了嗎?
如果我們禁用所有的 HTTP/1.x 的請(qǐng)求,是不是能通殺掉一大半爬蟲?requests 沒法用了,Scrapy 除非升級(jí)到最新版本才能勉強(qiáng)用個(gè)實(shí)驗(yàn)性版本,其他的語(yǔ)言也不用多說,也會(huì)殺一大部分。
而瀏覽器對(duì) HTTP/2.0 的支持現(xiàn)在已經(jīng)很好了,所以不會(huì)影響用戶瀏覽網(wǎng)頁(yè)的體驗(yàn)。
措施
那就讓我們來吧!
這個(gè)怎么做呢?其實(shí)很簡(jiǎn)單,在 Nginx 里面配置一下就好了,主要就是加這么個(gè)判斷就行了:
if ($server_protocol !~* "HTTP/2.0") {
return 444;
}
就是這么簡(jiǎn)單,這里 $server_protocol 就是傳輸協(xié)議,其結(jié)果目前有三個(gè):HTTP/1.0、HTTP/1.1 和 HTTP/2.0,另外判斷條件我們使用了 !~* ,意思就是不等于,這里的判斷條件就是,如果不是 HTTP/2.0,那就直接返回 444 狀態(tài)碼,444 一般代表 CONNECTION CLOSED WITHOUT RESPONSE,就是不返回任何結(jié)果關(guān)閉連接。
我的服務(wù)是在 Kubernetes 里面運(yùn)行的,所以要加這個(gè)配置還得改下 Nginx Ingress 的配置,不過還好 https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/ 預(yù)留了一個(gè)配置叫做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;
}
大功告成!
配置完成了,示例網(wǎng)站是:https://spa16.scrape.center/
我們?cè)跒g覽器中看下效果:
可以看到所有請(qǐng)求都是走的 HTTP/2.0,頁(yè)面完全正常加載。
然而,我們使用 requests 來請(qǐng)求一下:
import requests
response = requests.get('https://spa16.scrape.center/')
print(response.text)
非常歡樂的報(bào)錯(cuò):
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,無論如何都不行的,因?yàn)樗筒恢С?HTTP/2.0。
那我們換一個(gè)支持 HTTP/2.0 的庫(kù)呢?比如 httpx,安裝方法如下:
pip3 install 'httpx[http2]'
注意,Python 版本需要在 3.6 及以上才能用 httpx。
安裝好了之后測(cè)試下:
import httpx
client = httpx.Client(http2=True)
response = client.get('https://spa16.scrape.center/')
print(response.text)
結(jié)果如下:
<!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 的魔法!
我們?nèi)绻?nbsp;http2 參數(shù)設(shè)置為 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 燒香了!
又一個(gè)無敵反爬蟲誕生了!各大站長(zhǎng)們,安排起來吧~

最后我們會(huì)在本文的留言中選出三位粉絲送出紅包。
另外再選出六位粉絲免費(fèi)包郵贈(zèng)送書籍,書單如下:

推薦理由:本書以實(shí)戰(zhàn)技能的形式,講解了Python編程從入門到精通可能涉及的100個(gè)關(guān)鍵技能,從最基本的語(yǔ)法基礎(chǔ),到面向?qū)ο蟪绦蛟O(shè)計(jì),再到算法與數(shù)據(jù)結(jié)構(gòu),最后是基于Python的各種應(yīng)用,包括游戲、網(wǎng)站、數(shù)據(jù)分析與數(shù)據(jù)挖掘等。
推薦理由:本書堅(jiān)持以實(shí)例為主,理論為輔的路線,從 Python 基礎(chǔ)、爬蟲開發(fā)常用網(wǎng)絡(luò)請(qǐng)求庫(kù),到爬蟲框架使用和分布式爬蟲設(shè)計(jì),以及最后的數(shù)據(jù)存儲(chǔ)、分析、實(shí)戰(zhàn)訓(xùn)練等,覆蓋了爬蟲項(xiàng)目開發(fā)階段的整個(gè)生命周期。
推薦理由:由狗熊會(huì)推出的一本利用Python介紹數(shù)據(jù)科學(xué)基本過程的著作。本書以Python語(yǔ)言為基礎(chǔ),介紹利用Python進(jìn)行數(shù)據(jù)科學(xué)研究與商業(yè)分析的全貌。其核心的設(shè)計(jì)理念是通過經(jīng)典的商業(yè)應(yīng)用案例對(duì)數(shù)據(jù)爬取、數(shù)據(jù)存儲(chǔ)、數(shù)據(jù)清洗、數(shù)據(jù)建模的核心Python模塊做相應(yīng)的介紹
截止時(shí)間:
2021 年 5 月 24 日 16:00
2021-05-20
2021-05-20
2021-05-19
2021-05-18

