如何用 Python 偵測代理伺服器(逐步教學)
一篇 Python 教學:呼叫代理偵測 API,讀取代理類型與信心分數,並據此攔截請求,附可重用函式、快取方案及 Flask 範例。
2026年3月26日閱讀約 3 分鐘
本文是一篇面向 Python 後端的代理伺服器偵測實務教學。我們會將 代理偵測 API 封裝成一個可重用的函式,加入快取機制,並根據結果 攔截 Flask 路由。相同的做法同樣適用於 Django、FastAPI 或一般腳本。
事前準備
您需要一組 API 金鑰(免費方案已足夠用作測試)以及 requests 程式庫:
pip install requests
請將金鑰保存在環境變數中,切勿寫入原始碼。
開始撰寫程式碼前,先試用一次代理查詢
步驟一:撰寫可重用的偵測函式
import os
import requests
API_BASE = "https://ipscanner.io"
API_KEY = os.environ["IPSCANNER_API_KEY"]
def check_proxy(ip: str) -> dict:
"""Return {'is_proxy': bool, 'type': str|None, 'score': int}. Fails open."""
try:
resp = requests.get(
f"{API_BASE}/v1/proxy/{ip}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=3,
)
resp.raise_for_status()
data = resp.json()
return {
"is_proxy": bool(data.get("proxy")),
"type": data.get("type"),
"score": data.get("score", 0),
}
except requests.RequestException:
return {"is_proxy": False, "type": None, "score": 0} # fail open
「fail open」(失敗時放行)意味着即使偵測服務發生故障,亦不會將使用者拒諸門外。
步驟二:取得真實的客戶端 IP
在代理伺服器或負載平衡器之後,需讀取由您的基礎設施所設定的轉發標頭:
def client_ip(request) -> str:
xff = request.headers.get("X-Forwarded-For", "")
if xff:
return xff.split(",")[0].strip() # left-most = original client
return request.remote_addr
只有在您自行掌控的代理伺服器會設定該標頭時,才應信任 X-Forwarded-For。
步驟三:攔截 Flask 路由
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.post("/signup")
def signup():
ip = client_ip(request)
result = check_proxy(ip)
if result["score"] >= 70:
return jsonify(error="This network requires verification."), 403
if result["is_proxy"] or result["score"] >= 30:
# add friction instead of blocking: require email/phone verification
request.environ["require_verification"] = True
# ...create the account...
return jsonify(ok=True)
步驟四:加入短期快取
import time
_cache: dict[str, tuple[dict, float]] = {}
def check_proxy_cached(ip: str, ttl: int = 600) -> dict:
hit = _cache.get(ip)
if hit and hit[1] > time.time():
return hit[0]
value = check_proxy(ip)
_cache[ip] = (value, time.time() + ttl)
return value
TTL 宜設定在數分鐘的水平:IP 風險會隨時間改變,詳情可參閱 什麼是 IP 信譽 一文。
進階應用
總結
用 Python 偵測代理伺服器其實只需一次 API 呼叫:解析出真實的客戶端 IP,查詢後根據類型與分數 採取相應行動。發生錯誤時應保持放行,結果只作短期快取,並在中等風險區間要求額外驗證,而非 直接一律封鎖。
常見問題
常見問題解答
只需要一個 HTTP 客戶端,例如 requests(或 httpx)。呼叫代理偵測 API 的端點並讀取 JSON 回應即可,不需要任何特別的程式庫。