超強反爬蟲方案!Requests 什麼的通通爬不了

上一篇文章再見 HTTP 1.1,怎樣把網站升級成 HTTP 2?介紹瞭如何升級網站到 HTTP/2.0,但是實際上並沒有顯式地聲明禁用 HTTP 1.x 的請求。

想到這裏,你可能就想到了一個非常強的反爬蟲方案 —— 禁用所有 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 的支持也不好,目前對 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.1HTTP/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/

我們在瀏覽器中看下效果:

可以看到所有請求都是走的 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 ><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 燒香了!

又一個無敵反爬蟲誕生了!各大站長們,安排起來吧~

作者:崔慶才

排版:崔慶才

同名公衆號「崔慶才丨靜覓」

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/dFxyRYmqm5if8k-S1MjFJw