Requests什么的通通爬不了的Python超強(qiáng)反爬蟲方案!
一、
一個非常強(qiáng)的反爬蟲方案 ——禁用所有 HTTP 1.x 的請求!
現(xiàn)在很多爬蟲庫其實(shí)對 HTTP/2.0 支持得不好,比如大名鼎鼎的 Python 庫 —— requests,到現(xiàn)在為止還只支持 HTTP/1.1,啥時候支持 HTTP/2.0 還不知道。
Scrapy 框架最新版本 2.5.0(2021.04.06 發(fā)布)加入了對 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
信號。
關(guān)于其他的一些庫,也不必多說了,對 HTTP/2.0 的支持也不好,目前對 HTTP/2.0 支持得還可以的有 hyper 和 httpx,后者更加簡單易用一些。
二、反爬蟲
所以,你想到反爬蟲方案了嗎?
如果我們禁用所有的 HTTP/1.x 的請求,是不是能通殺掉一大半爬蟲?requests 沒法用了,Scrapy 除非升級到最新版本才能勉強(qiáng)用個實(shí)驗(yàn)性版本,其他的語言也不用多說,也會殺一大部分。
而瀏覽器對 HTTP/2.0 的支持現(xiàn)在已經(jīng)很好了,所以不會影響用戶瀏覽網(wǎng)頁的體驗(yàn)。
三、措施
那就讓我們來吧!
這個怎么做呢?其實(shí)很簡單,在 Nginx 里面配置一下就好了,主要就是加這么個判斷就行了:
if ($server_protocol !~* "HTTP/2.0") { return 444; }
就是這么簡單,這里$server_protocol
就是傳輸協(xié)議,其結(jié)果目前有三個: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)行的,所以要加這個配置還得改下 Nginx Ingress 的配置,不過還好https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/預(yù)留了一個配置叫做nginx.ingress.kubernetes.io/server-snippet
,利用它我們可以自定義 Nginx 的判定邏輯。
官方用法如下:
apiVersion:networking.k8s.io/v1beta1 kind:Ingress metadata: annotations: nginx.ingress.kubernetes.io/server-snippet:| set$agentflag0; if($http_user_agent~*"(Mobile)"){ set$agentflag1; } if($agentflag=1){ return301https://m.example.com; }
所以這里,我們只需要改成剛才的配置就好了:
apiVersion:networking.k8s.io/v1beta1 kind:Ingress metadata: annotations: nginx.ingress.kubernetes.io/server-snippet:| if($server_protocol!~*"HTTP/2.0"){ return444; }
大功告成!
配置完成了,示例網(wǎng)站是:https://spa16.scrape.center/
我們在瀏覽器中看下效果:
可以看到所有請求都是走的 HTTP/2.0,頁面完全正常加載。
然而,我們使用 requests 來請求一下:
import requests response = requests.get('https://spa16.scrape.center/') print(response.text)
非常歡樂的報錯:
Traceback(mostrecentcalllast): ... raiseRemoteDisconnected("Remoteendclosedconnectionwithout" http.client.RemoteDisconnected:Remoteendclosedconnectionwithoutresponse Duringhandlingoftheaboveexception,anotherexceptionoccurred: Traceback(mostrecentcalllast): ... raiseMaxRetryError(_pool,url,errororResponseError(cause)) requests.packages.urllib3.exceptions.MaxRetryError:HTTPSConnectionPool(host='spa16.scrape.center',port=443):Maxretriesexceededwithurl:/(CausedbyProxyError('Cannotconnecttoproxy.',RemoteDisconnected('Remoteendclosedconnectionwithoutresponse'))) Duringhandlingoftheaboveexception,anotherexceptionoccurred: Traceback(mostrecentcalllast): ... requests.exceptions.ProxyError:HTTPSConnectionPool(host='spa16.scrape.center',port=443):Maxretriesexceededwithurl:/(CausedbyProxyError('Cannotconnecttoproxy.',RemoteDisconnected('Remoteendclosedconnectionwithoutresponse')))
如果你用 requests,無論如何都不行的,因?yàn)樗筒恢С?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)
結(jié)果如下:
<!DOCTYPEhtml><htmllang=en><head><metacharset=utf-8><metahttp-equiv=X-UA-Compatiblecontent="IE=edge"><metaname=viewportcontent="width=device-width,initial-scale=1"><metaname=referrercontent=no-referrer><linkrel=iconhref=/favicon.ico><title>Scrape|Book</title><linkhref=/css/chunk-50522e84.e4e1dae6.cssrel=prefetch><linkhref=/css/chunk-f52d396c.4f574d24.cssrel=prefetch><linkhref=/js/chunk-50522e84.6b3e24aa.jsrel=prefetch><linkhref=/js/chunk-f52d396c.f8f41620.jsrel=prefetch><linkhref=/css/app.ea9d802a.cssrel=preloadas=style><linkhref=/js/app.b93891e2.jsrel=preloadas=script><linkhref=/js/chunk-vendors.a02ff921.jsrel=preloadas=script><linkhref=/css/app.ea9d802a.cssrel=stylesheet></head><body><noscript><strong>We'resorrybutportaldoesn'tworkproperlywithoutJavaScriptenabled.Pleaseenableittocontinue.</strong></noscript><divid=app></div><scriptsrc=/js/chunk-vendors.a02ff921.js></script><scriptsrc=/js/app.b93891e2.js></script></body></html>
可以看到,HTML 就成功被我們獲取到了!這就是 HTTP/2.0 的魔法!
我們?nèi)绻?code>http2參數(shù)設(shè)置為 False 呢?
import httpx client = httpx.Client(http2=False) response = client.get('https://spa16.scrape.center/') print(response.text)
一樣很不幸:
Traceback(mostrecentcalllast): ... raiseRemoteProtocolError(msg) httpcore.RemoteProtocolError:Serverdisconnectedwithoutsendingaresponse. Theaboveexceptionwasthedirectcauseofthefollowingexception: ... raisemapped_exc(message)fromexc httpx.RemoteProtocolError:Serverdisconnectedwithoutsendingaresponse.
所以,這就印證了,只要 HTTP/1.x 通通沒法治!可以給 requests 燒香了!
又一個無敵反爬蟲誕生了!各大站長們,安排起來吧~
到此這篇關(guān)于Requests什么的通通爬不了的Python超強(qiáng)反爬蟲方案!的文章就介紹到這了,更多相關(guān)Python反爬蟲內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。