App下載

Python超強(qiáng)反爬蟲(chóng)方案!如何禁用request庫(kù)請(qǐng)求?

猿友 2021-07-23 13:58:22 瀏覽數(shù) (2453)
反饋

隨著近些年python大火,很多人有或多或少學(xué)習(xí)過(guò)一點(diǎn)python,而爬蟲(chóng)的技術(shù)又相對(duì)比較簡(jiǎn)單,這就導(dǎo)致了很多學(xué)有小成的爬蟲(chóng)開(kāi)發(fā)者待著自己的爬蟲(chóng)在你的網(wǎng)站上爬取數(shù)據(jù),對(duì)于大站而言,一些小小的爬蟲(chóng)并不會(huì)太多地影響他站點(diǎn)的運(yùn)營(yíng)。但小站就不一樣了,輕則影響其他人的服務(wù)效果,重則爬蟲(chóng)掏干凈了你的庫(kù),然后你的創(chuàng)作就不值錢(qián)了,那么作為一個(gè)站長(zhǎng),怎么進(jìn)行python爬蟲(chóng)反爬呢?其實(shí)有一個(gè)比較簡(jiǎn)單的操作——使用http2.0。

一、前言

一個(gè)非常強(qiáng)的反爬蟲(chóng)方案 —— 禁用所有 HTTP 1.x 的請(qǐng)求!

現(xiàn)在很多爬蟲(chóng)庫(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)闆](méi)有主流瀏覽器支持未加密的 HTTP/2.0。
  • 沒(méi)有用于指定最大幀大小大于默認(rèn)值 16384 的設(shè)置,發(fā)送更大幀的服務(wù)器的連接將失敗。
  • 不支持服務(wù)器推送。
  • 不支持bytes_received和 headers_received信號(hào)。

關(guān)于其他的一些庫(kù),也不必多說(shuō)了,對(duì) HTTP/2.0 的支持也不好,目前對(duì) HTTP/2.0 支持得還可以的有 hyper 和 httpx,后者更加簡(jiǎn)單易用一些。

二、反爬蟲(chóng)

所以,你想到反爬蟲(chóng)方案了嗎?

如果我們禁用所有的 HTTP/1.x 的請(qǐng)求,是不是能通殺掉一大半爬蟲(chóng)?requests 沒(méi)法用了,Scrapy 除非升級(jí)到最新版本才能勉強(qiáng)用個(gè)實(shí)驗(yàn)性版本,其他的語(yǔ)言也不用多說(shuō),也會(huì)殺一大部分。

而瀏覽器對(duì) HTTP/2.0 的支持現(xiàn)在已經(jīng)很好了,所以不會(huì)影響用戶瀏覽網(wǎng)頁(yè)的體驗(yàn)。

三、措施

那就讓我們來(lái)吧!

這個(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 的配置,不過(guò)還好 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覽器中看下效果:

Image

可以看到所有請(qǐng)求都是走的 HTTP/2.0,頁(yè)面完全正常加載。

然而,我們使用 requests 來(lái)請(qǐng)求一下:

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

非常歡樂(lè)的報(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,無(wú)論如何都不行的,因?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 通通沒(méi)法治!可以給 requests 燒香了!

又一個(gè)無(wú)敵反爬蟲(chóng)誕生了!各大站長(zhǎng)們,安排起來(lái)吧~

到此這篇通過(guò)如何禁用Requests庫(kù)請(qǐng)求的方式來(lái)進(jìn)行python爬蟲(chóng)反爬對(duì)方文章就介紹到這里,更多Python反爬蟲(chóng)相關(guān)技術(shù)內(nèi)容請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章。

0 人點(diǎn)贊