Cloudflare Turnstile đang thay thế CAPTCHA truyền thống trên hàng triệu trang web. Hướng dẫn này chỉ cho bạn cách giải quyết các thử thách trong Cloudflare Turnstile bằng thư viện requests của Python và API của CaptchaAI — với tỷ lệ thành công 100%.
Điều kiện tiên quyết
pip install requests
Bạn cần:
- Khóa API CaptchaAI từcaptchaai.com
- URL trang đích
- Khóa trang web Turnstile
Bước 1: Trích xuất khóa trang web Turnstile
import re
import requests
def extract_turnstile_sitekey(url):
"""Extract Cloudflare Turnstile sitekey from page HTML."""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/120.0.0.0",
"Accept": "text/html,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
}
response = requests.get(url, headers=headers, timeout=15)
patterns = [
r'data-sitekey=["\']([0-9x][A-Za-z0-9_-]+)["\']',
r"sitekey\s*:\s*['\"]([0-9x][A-Za-z0-9_-]+)['\"]",
r"siteKey\s*[=:]\s*['\"]([0-9x][A-Za-z0-9_-]+)['\"]",
]
for pattern in patterns:
match = re.search(pattern, response.text)
if match:
return match.group(1)
return None
sitekey = extract_turnstile_sitekey("https://example.com/signup")
print(f"Sitekey: {sitekey}")
Bước 2: Gửi tới CaptchaAI
import requests
API_KEY = "YOUR_API_KEY"
def submit_turnstile(sitekey, page_url):
"""Submit Turnstile solving task to CaptchaAI."""
response = requests.post("https://ocr.captchaai.com/in.php", data={
"key": API_KEY,
"method": "turnstile",
"sitekey": sitekey,
"pageurl": page_url,
"json": 1,
})
data = response.json()
if data.get("status") != 1:
raise Exception(f"Submit failed: {data.get('request')}")
return data["request"]
task_id = submit_turnstile("0x4AAAAAAAC3DHQhMMQ_Rxrg", "https://example.com/signup")
print(f"Task ID: {task_id}")
Bước 3: Thăm dò kết quả
import time
def poll_result(task_id, timeout=120):
"""Poll CaptchaAI for the solved Turnstile token."""
start = time.time()
while time.time() - start < timeout:
time.sleep(5)
result = requests.get("https://ocr.captchaai.com/res.php", params={
"key": API_KEY,
"action": "get",
"id": task_id,
"json": 1,
}).json()
if result.get("status") == 1:
return result["request"]
if result.get("request") == "ERROR_CAPTCHA_UNSOLVABLE":
raise Exception("Turnstile could not be solved")
raise TimeoutError("Solve timed out")
token = poll_result(task_id)
print(f"Token: {token[:50]}...")
Hoàn thành ví dụ làm việc
import re
import time
import requests
API_KEY = "YOUR_API_KEY"
TARGET_URL = "https://example.com/signup"
def solve_turnstile(sitekey, page_url):
"""Full Turnstile solve: submit + poll."""
# Submit
submit = requests.post("https://ocr.captchaai.com/in.php", data={
"key": API_KEY,
"method": "turnstile",
"sitekey": sitekey,
"pageurl": page_url,
"json": 1,
})
data = submit.json()
if data.get("status") != 1:
raise Exception(f"Submit error: {data.get('request')}")
task_id = data["request"]
print(f"Task submitted: {task_id}")
# Poll
for _ in range(30):
time.sleep(5)
result = requests.get("https://ocr.captchaai.com/res.php", params={
"key": API_KEY,
"action": "get",
"id": task_id,
"json": 1,
}).json()
if result.get("status") == 1:
return result["request"]
raise TimeoutError("Solve timed out")
# --- Main flow ---
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/120.0.0.0",
"Accept": "text/html,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
})
# 1. Get page and extract sitekey
response = session.get(TARGET_URL, timeout=15)
match = re.search(r'data-sitekey=["\']([0-9x][A-Za-z0-9_-]+)["\']', response.text)
if not match:
raise ValueError("Turnstile sitekey not found")
sitekey = match.group(1)
print(f"Sitekey: {sitekey}")
# 2. Solve Turnstile
token = solve_turnstile(sitekey, TARGET_URL)
print(f"Token: {token[:50]}...")
# 3. Submit form with token
form_response = session.post(TARGET_URL, data={
"cf-turnstile-response": token,
"email": "user@example.com",
"password": "SecurePass123",
})
print(f"Form status: {form_response.status_code}")
Xử lý Turnstile với tham số hành động
Một số trang web xác thực phía máy chủ tham số action:
def solve_turnstile_with_action(sitekey, page_url, action):
"""Solve Turnstile that requires an action parameter."""
submit = requests.post("https://ocr.captchaai.com/in.php", data={
"key": API_KEY,
"method": "turnstile",
"sitekey": sitekey,
"pageurl": page_url,
"action": action, # Include the action from data-action attribute
"json": 1,
})
data = submit.json()
if data.get("status") != 1:
raise Exception(f"Submit error: {data.get('request')}")
task_id = data["request"]
for _ in range(30):
time.sleep(5)
result = requests.get("https://ocr.captchaai.com/res.php", params={
"key": API_KEY,
"action": "get",
"id": task_id,
"json": 1,
}).json()
if result.get("status") == 1:
return result["request"]
raise TimeoutError("Solve timed out")
Mẫu gửi mã thông báo
Mẫu 1: Biểu mẫu POST với cf-turnstile-response
# Most common — Turnstile uses cf-turnstile-response field
response = session.post(form_url, data={
"cf-turnstile-response": token,
"email": "user@example.com",
})
Mẫu 2: API JSON
response = session.post(api_url, json={
"turnstileToken": token,
"email": "user@example.com",
})
Mẫu 3: Tên trường tùy chỉnh
# Some sites rename the field — check the form HTML
response = session.post(form_url, data={
"cf-turnstile-response": token,
"captcha_token": token, # Custom duplicate field
"action": "signup",
})
Lớp sẵn sàng sản xuất
import re
import time
import requests
class TurnstileSolver:
"""Production-ready Turnstile solver with retry logic."""
API_URL = "https://ocr.captchaai.com"
def __init__(self, api_key, max_retries=3):
self.api_key = api_key
self.max_retries = max_retries
def extract_sitekey(self, session, url):
"""Extract Turnstile sitekey from page."""
response = session.get(url, timeout=15)
match = re.search(
r'data-sitekey=["\']([0-9x][A-Za-z0-9_-]+)["\']', response.text
)
return match.group(1) if match else None
def solve(self, sitekey, page_url, action=None):
"""Solve Turnstile with retry logic. Returns token string."""
for attempt in range(1, self.max_retries + 1):
try:
token = self._solve_once(sitekey, page_url, action)
return token
except TimeoutError:
print(f"Attempt {attempt} timed out")
except Exception as e:
error_str = str(e)
if "ERROR_ZERO_BALANCE" in error_str:
raise # Don't retry billing errors
if "ERROR_WRONG_USER_KEY" in error_str:
raise
print(f"Attempt {attempt} failed: {e}")
raise Exception(f"Failed after {self.max_retries} attempts")
def _solve_once(self, sitekey, page_url, action=None):
"""Single solve attempt."""
params = {
"key": self.api_key,
"method": "turnstile",
"sitekey": sitekey,
"pageurl": page_url,
"json": 1,
}
if action:
params["action"] = action
submit = requests.post(f"{self.API_URL}/in.php", data=params, timeout=30)
submit.raise_for_status()
data = submit.json()
if data.get("status") != 1:
raise Exception(f"Submit error: {data.get('request')}")
task_id = data["request"]
for _ in range(30):
time.sleep(5)
result = requests.get(f"{self.API_URL}/res.php", params={
"key": self.api_key,
"action": "get",
"id": task_id,
"json": 1,
}, timeout=30).json()
if result.get("status") == 1:
return result["request"]
if result.get("request") == "ERROR_CAPTCHA_UNSOLVABLE":
raise Exception("CAPTCHA unsolvable")
raise TimeoutError("Poll timed out")
# Usage
solver = TurnstileSolver("YOUR_API_KEY")
token = solver.solve("0x4AAAAAAAC3DHQhMMQ_Rxrg", "https://example.com/signup")
Khắc phục sự cố
| Triệu chứng | nguyên nhân | sửa chữa |
|---|---|---|
| Đã nhận được mã thông báo nhưng biểu mẫu bị từ chối | Khóa trang web sai hoặc thiếu hành động | Trích xuất lại khóa trang web, bao gồm hành động nếu có |
| "Không tìm thấy khóa trang web" | Cloudflare Turnstile được tải qua JavaScript | Sử dụng Selenium cho các trang động |
| HTTP 403 trước khi nhận trang | Yêu cầu chặn BIC của Cloudflare | Thêm tiêu đề trình duyệt thích hợp |
| Giải quyết mất >60 giây | Tắc nghẽn hàng đợi | Bình thường vào thời gian cao điểm, chờ lâu hơn |
| Mã thông báo hoạt động một lần rồi thất bại | Trang web yêu cầu mã thông báo mới cho mỗi lần thử | Giải quyết một mã thông báo mới cho mỗi lần gửi |
Câu hỏi thường gặp
Tỷ lệ thành công là bao nhiêu?
CaptchaAI đạt tỷ lệ thành công 100% trên Cloudflare Turnstile trên tất cả các chế độ tiện ích.
Việc giải quyết mất bao lâu?
Thời gian giải quyết điển hình là 5-15 giây. Turnstile thường nhanh hơn reCAPTCHA.
Chế độ Turnstile có quan trọng không?
Không. Tất cả các chế độ được quản lý, không tương tác và ẩn đều sử dụng cùng một lệnh gọi API. CaptchaAI xử lý sự khác biệt về chế độ trong nội bộ.
Điều gì sẽ xảy ra nếu trang có cả Turnstile và reCAPTCHA?
Không phổ biến nhưng có thể. Xác định CAPTCHA nào bảo vệ biểu mẫu bạn đang gửi và giải quyết biểu mẫu đó. Họ sử dụng tên trường phản hồi khác nhau.
Tóm tắt
Giải Cloudflare Turnstile bằng Python requests yêu cầu ba bước: trích xuất khóa trang web từ trang HTML, gửi tớiCaptchaAIsử dụng method=turnstile và thăm dò mã thông báo. Gửi mã thông báo dưới dạng cf-turnstile-response trong dữ liệu biểu mẫu của bạn. CaptchaAI mang lại tỷ lệ thành công 100% trên tất cả các chế độ Cloudflare Turnstile.