Tutorial

如何用 Python 绕过 Cloudflare Challenge(托管质询)

2026-04-146 分钟阅读

Cloudflare 的托管质询(也叫 JS Challenge)是一个全页面的「正在检查您的浏览器」拦截页,用于阻止机器人。与返回令牌的 Turnstile 不同,Challenge 会设置绑定特定 IP 地址的 cf_clearance Cookie。在本教程中,您将学习如何使用 Python、代理和 NSLSolver API 来绕过它。

Challenge 与 Turnstile — 有什么区别?

Turnstile 是一个嵌入式小部件,返回一个令牌供您提交表单。Challenge 是一个全页面拦截页,设置与访客 IP 绑定的 cf_clearance Cookie。由于 Cookie 与 IP 绑定,解决时必须使用代理 — 后续请求也必须使用相同的代理。

前置条件

  • 已安装 Python 3.7 或更高版本
  • requests 库(pip install requests)
  • 一个可用的 HTTP/HTTPS 代理(Cookie 与 IP 绑定)
  • NSLSolver API 密钥 — 免费注册

第一步:安装依赖

您只需要 requests 库。使用 pip 安装:

terminal
$pip install requests

第二步:获取 API 密钥

使用 NSLSolver API 需要一个 API 密钥:

  1. 在 nslsolver.com 创建免费账户
  2. 验证邮箱即可获得 100 次免费请求
  3. 从控制台复制您的 API 密钥

第三步:使用代理发送解决请求

发送包含 type "challenge"、目标 URL 和代理的 POST 请求。代理是必需的,因为 cf_clearance Cookie 与解决质询时的 IP 绑定:

solve_challenge.py
import requests

API_KEY = "nsl_YOUR_API_KEY"

response = requests.post(
    "https://api.nslsolver.com/solve",
    headers={"X-API-Key": API_KEY},
    json={
        "type": "challenge",
        "url": "https://example.com/protected-page",
        "proxy": "http://user:[email protected]:8080"
    }
)

data = response.json()
print(data["cookies"])
print(data["user_agent"])

重要提示:challenge 类型必须提供 proxy 字段。cf_clearance Cookie 只有在请求来自解决质询时使用的同一 IP 地址时才有效。如果您省略代理或后续请求使用不同的代理,Cloudflare 将拒绝该 Cookie。

API 返回的 Cookie 和 user_agent 必须一起使用:

response.json
{
  "success": true,
  "cookies": {
    "cf_clearance": "aBcDeFgHiJkLmNoPqRsTuVwXyZ..."
  },
  "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...",
  "cost": 0.002
}

第四步:使用相同代理发送带 Cookie 的请求

使用返回的 Cookie、用户代理和相同的代理访问受保护页面。三者必须匹配,Cloudflare 才会接受请求:

use_cookies.py
# After getting cookies + user_agent from NSLSolver:
cookies = data["cookies"]
user_agent = data["user_agent"]

# Use the SAME proxy that was used to solve
proxies = {
    "http": "http://user:[email protected]:8080",
    "https": "http://user:[email protected]:8080"
}

# Make request with matching cookies, user agent, and proxy
result = requests.get(
    "https://example.com/protected-page",
    headers={"User-Agent": user_agent},
    cookies=cookies,
    proxies=proxies
)

print(result.status_code)  # 200 = success!

完整示例(含错误处理)

以下是适用于生产环境的示例,包含重试、错误处理和 requests.Session 的 Cookie 持久化:

challenge_bypass.py
import requests
import time

API_KEY  = "nsl_YOUR_API_KEY"
TARGET_URL = "https://example.com/protected-page"
PROXY    = "http://user:[email protected]:8080"


def solve_challenge(url, proxy, retries=3):
    """Solve a Cloudflare Challenge via NSLSolver."""
    for attempt in range(retries):
        try:
            resp = requests.post(
                "https://api.nslsolver.com/solve",
                headers={"X-API-Key": API_KEY},
                json={
                    "type": "challenge",
                    "url": url,
                    "proxy": proxy
                },
                timeout=60
            )
            resp.raise_for_status()
            data = resp.json()

            if data.get("success"):
                return data

            print(f"Attempt {attempt + 1} failed: {data}")

        except requests.RequestException as e:
            print(f"Request error: {e}")

        if attempt < retries - 1:
            time.sleep(3)

    return None


# Solve the challenge
solution = solve_challenge(TARGET_URL, PROXY)

if solution:
    print("Challenge solved! Fetching protected page...")

    # Build session with solved cookies + user agent
    session = requests.Session()
    session.headers["User-Agent"] = solution["user_agent"]
    session.cookies.update(solution["cookies"])
    session.proxies = {
        "http": PROXY,
        "https": PROXY
    }

    # Fetch the protected page
    result = session.get(TARGET_URL)
    print(f"Status: {result.status_code}")
    print(result.text[:500])
else:
    print("Failed to solve challenge after retries.")

常见错误

调用 API 时可能遇到的 HTTP 状态码:

  • 401API 密钥无效。请检查您的 X-API-Key 请求头。
  • 402余额不足。请为账户充值。
  • 422缺少必填字段。challenge 类型需要同时提供 "url" 和 "proxy"。
  • 429请求被限流。请稍等片刻后重试。
  • 500服务器错误。请重试请求。如果持续出现,请联系客服。

小贴士:challenge 类型请使用静态/粘性代理。轮转代理会破坏 IP 绑定,使 cf_clearance Cookie 失效。该 Cookie 通常有效期为 15-30 分钟,在此期间可以重复使用。

准备好绕过 Cloudflare Challenge 了吗?

创建免费账户,获取 100 次请求体验。无需信用卡。