App下載

Python超強(qiáng)反爬蟲方案!如何禁用request庫請求?

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

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

一、前言

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

現(xiàn)在很多爬蟲庫其實(shí)對 HTTP/2.0 支持得不好,比如大名鼎鼎的 Python 庫 —— requests,到現(xiàn)在為止還只支持 HTTP/1.1,啥時(shí)候支持 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)用個(gè)實(shí)驗(yàn)性版本,其他的語言也不用多說,也會殺一大部分。

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

三、措施

那就讓我們來吧!

這個(gè)怎么做呢?其實(shí)很簡單,在 Nginx 里面配置一下就好了,主要就是加這么個(gè)判斷就行了:

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

就是這么簡單,這里 $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/

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

Image

可以看到所有請求都是走的 HTTP/2.0,頁面完全正常加載。

然而,我們使用 requests 來請求一下:

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 的庫呢?比如 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é)果如下:

<!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è)無敵反爬蟲誕生了!各大站長們,安排起來吧~

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

0 人點(diǎn)贊