Para enviar um Cloudflare Turnstile à resolução via API, você precisa de duas informações: a sitekey e a URL da página. O Turnstile nem sempre é exposto do mesmo jeito — direto no HTML, só via JavaScript, ou só após interação do usuário. Um script que busca apenas data-sitekey falha em boa parte dos sites. Este guia cobre os três padrões, com código pronto para cada um.
Como o Turnstile aparece no HTML
Três formas de incorporação, três abordagens de detecção:
| Implementação | Como funciona | Dificuldade |
|---|---|---|
| HTML implícito | <div class="cf-turnstile" data-sitekey="..."> na página |
Fácil |
| JavaScript explícito | turnstile.render() em um script |
Médio |
| Carregamento dinâmico | Widget após ação do usuário ou XHR | Difícil |
Método 1: verificar o HTML estático da página
A integração mais simples usa a classe cf-turnstile com data-sitekey. Se o site renderiza no servidor, sem esperar JavaScript, basta buscar a página e aplicar regex — sem navegador:
import re
import requests
def detect_turnstile_html(url):
"""Detect Turnstile from static 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)
html = response.text
result = {
"turnstile_found": False,
"sitekey": None,
"mode": None,
"theme": None,
"action": None,
"script_loaded": False,
}
# Check for Turnstile script
if "challenges.cloudflare.com/turnstile" in html:
result["script_loaded"] = True
# Check for widget container
if "cf-turnstile" in html:
result["turnstile_found"] = True
# Extract sitekey
sitekey_match = re.search(
r'data-sitekey=["\']([0-9x][A-Za-z0-9_-]+)["\']', html
)
if sitekey_match:
result["sitekey"] = sitekey_match.group(1)
# Extract mode
if 'data-size="invisible"' in html:
result["mode"] = "invisible"
elif 'data-appearance="interaction-only"' in html:
result["mode"] = "non-interactive"
else:
result["mode"] = "managed"
# Extract theme
theme_match = re.search(r'data-theme=["\'](\w+)["\']', html)
if theme_match:
result["theme"] = theme_match.group(1)
# Extract action
action_match = re.search(r'data-action=["\']([^"\']+)["\']', html)
if action_match:
result["action"] = action_match.group(1)
return result
# Usage
info = detect_turnstile_html("https://staging.example.com/qa-login")
if info["turnstile_found"]:
print(f"Sitekey: {info['sitekey']}")
print(f"Mode: {info['mode']}")
A função também identifica o modo (managed, non-interactive ou invisible) e o data-action, usados na chamada de resolução mais adiante.
Método 2: identificar a chamada turnstile.render()
Alguns sites não colocam data-sitekey no HTML — chamam turnstile.render() num script, passando a sitekey num objeto de configuração. A extração mira o corpo da função, não a tag:
import re
def detect_turnstile_js_api(html):
"""Detect Turnstile from JavaScript render calls."""
patterns = [
# turnstile.render('#element', {sitekey: '...'})
r"turnstile\.render\s*\(\s*['\"]([^'\"]+)['\"]\s*,\s*\{([^}]+)\}",
# turnstile.render(element, {sitekey: '...'})
r"turnstile\.render\s*\([^,]+,\s*\{([^}]+)\}",
]
for pattern in patterns:
match = re.search(pattern, html, re.DOTALL)
if match:
config_text = match.group(match.lastindex)
# Extract sitekey from config object
sitekey_match = re.search(
r"sitekey\s*:\s*['\"]([0-9x][A-Za-z0-9_-]+)['\"]", config_text
)
# Extract callback
callback_match = re.search(
r"callback\s*:\s*(\w+|function)", config_text
)
# Extract action
action_match = re.search(
r"action\s*:\s*['\"]([^'\"]+)['\"]", config_text
)
# Extract appearance
appearance_match = re.search(
r"appearance\s*:\s*['\"]([^'\"]+)['\"]", config_text
)
return {
"found": True,
"method": "javascript_api",
"sitekey": sitekey_match.group(1) if sitekey_match else None,
"callback": callback_match.group(1) if callback_match else None,
"action": action_match.group(1) if action_match else None,
"appearance": appearance_match.group(1) if appearance_match else None,
}
return {"found": False, "method": None}
Comum em SPAs e checkouts que montam o formulário via JS após o carregamento inicial.
Método 3: capturar o widget carregado dinamicamente (Selenium/Puppeteer)
Quando o Turnstile só surge após uma ação do usuário, nem o HTML nem o JS inicial trazem a sitekey. A forma confiável é renderizar a página com Selenium ou Puppeteer e ler o DOM após o widget carregar.
Python (Selenium)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
def detect_turnstile_dynamic(url):
"""Detect dynamically loaded Turnstile using Selenium."""
options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
try:
driver.get(url)
# Wait for page to fully load
WebDriverWait(driver, 10).until(
lambda d: d.execute_script("return document.readyState") == "complete"
)
result = {
"turnstile_found": False,
"sitekey": None,
"iframe_present": False,
"response_field": False,
}
# Check for Turnstile iframe
iframes = driver.find_elements(By.CSS_SELECTOR, "iframe[src*='challenges.cloudflare.com']")
if iframes:
result["turnstile_found"] = True
result["iframe_present"] = True
# Check for cf-turnstile container
containers = driver.find_elements(By.CSS_SELECTOR, ".cf-turnstile, [data-sitekey]")
for container in containers:
sitekey = container.get_attribute("data-sitekey")
if sitekey:
result["turnstile_found"] = True
result["sitekey"] = sitekey
# Check for hidden response field
response_fields = driver.find_elements(
By.CSS_SELECTOR, "[name='cf-turnstile-response'], [name='g-recaptcha-response']"
)
if response_fields:
result["response_field"] = True
# Check page source for JS API render
page_source = driver.page_source
js_match = re.search(
r"sitekey\s*:\s*['\"]([0-9x][A-Za-z0-9_-]+)['\"]", page_source
)
if js_match and not result["sitekey"]:
result["sitekey"] = js_match.group(1)
result["turnstile_found"] = True
return result
finally:
driver.quit()
Node.js (Puppeteer)
const puppeteer = require("puppeteer");
async function detectTurnstileDynamic(url) {
const browser = await puppeteer.launch({
headless: "new",
args: ["--disable-blink-features=AutomationControlled"],
});
const page = await browser.newPage();
const result = {
turnstileFound: false,
sitekey: null,
iframePresent: false,
responseField: false,
scriptUrl: null,
};
// Monitor network for Turnstile script
page.on("response", (response) => {
if (response.url().includes("challenges.cloudflare.com/turnstile")) {
result.scriptUrl = response.url();
}
});
await page.goto(url, { waitUntil: "networkidle2" });
// Check for Turnstile container
const sitekey = await page.evaluate(() => {
const el = document.querySelector(
".cf-turnstile, [data-sitekey]"
);
return el ? el.getAttribute("data-sitekey") : null;
});
if (sitekey) {
result.turnstileFound = true;
result.sitekey = sitekey;
}
// Check for Turnstile iframe
const iframes = await page.$$("iframe[src*='challenges.cloudflare.com']");
if (iframes.length > 0) {
result.turnstileFound = true;
result.iframePresent = true;
}
// Check for response field
const responseField = await page.$(
"[name='cf-turnstile-response']"
);
result.responseField = !!responseField;
await browser.close();
return result;
}
detectTurnstileDynamic("https://staging.example.com/qa-login").then(console.log);
Os dois exemplos checam três sinais: iframe do desafio, contêiner .cf-turnstile e o campo cf-turnstile-response — combiná-los reduz falso negativo.
Uma classe Python que reúne os três métodos
A classe abaixo tenta os três métodos em sequência e devolve um resultado consolidado: sitekey, modo e tipo de implementação.
import re
import requests
class TurnstileDetector:
"""Detect Cloudflare Turnstile across all implementation methods."""
TURNSTILE_SCRIPT = "challenges.cloudflare.com/turnstile"
SITEKEY_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_-]+)['\"]",
r"TURNSTILE_SITE_KEY\s*[=:]\s*['\"]([0-9x][A-Za-z0-9_-]+)['\"]",
]
def __init__(self, url, html=None):
self.url = url
self.html = html
if not self.html:
self._fetch()
def _fetch(self):
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(self.url, headers=headers, timeout=15)
self.html = response.text
def detect(self):
"""Run all detection methods and return results."""
return {
"url": self.url,
"turnstile_present": self.has_turnstile(),
"sitekey": self.extract_sitekey(),
"mode": self.detect_mode(),
"implementation": self.detect_implementation(),
"script_loaded": self.has_script(),
"response_field": self.has_response_field(),
"action": self.extract_action(),
"theme": self.extract_theme(),
}
def has_turnstile(self):
return (
self.has_script()
or "cf-turnstile" in self.html
or self.extract_sitekey() is not None
)
def has_script(self):
return self.TURNSTILE_SCRIPT in self.html
def has_response_field(self):
return "cf-turnstile-response" in self.html
def extract_sitekey(self):
for pattern in self.SITEKEY_PATTERNS:
match = re.search(pattern, self.html)
if match:
return match.group(1)
return None
def detect_mode(self):
if 'data-size="invisible"' in self.html or "size: 'invisible'" in self.html:
return "invisible"
if 'data-appearance="interaction-only"' in self.html:
return "non-interactive"
if "cf-turnstile" in self.html:
return "managed"
return "unknown"
def detect_implementation(self):
if "cf-turnstile" in self.html and re.search(r"data-sitekey=", self.html):
return "html_implicit"
if "turnstile.render" in self.html:
return "javascript_explicit"
if self.has_script() and not "cf-turnstile" in self.html:
return "dynamic_loading"
return "unknown"
def extract_action(self):
match = re.search(r'data-action=["\']([^"\']+)["\']', self.html)
if match:
return match.group(1)
match = re.search(r"action\s*:\s*['\"]([^'\"]+)['\"]", self.html)
return match.group(1) if match else None
def extract_theme(self):
match = re.search(r'data-theme=["\'](\w+)["\']', self.html)
return match.group(1) if match else "auto"
# Usage
detector = TurnstileDetector("https://staging.example.com/qa-login")
info = detector.detect()
if info["turnstile_present"]:
print(f"Sitekey: {info['sitekey']}")
print(f"Mode: {info['mode']}")
print(f"Implementation: {info['implementation']}")
Do sitekey à resolução: enviando para a CaptchaAI
Com a sitekey em mãos, envie a tarefa à CaptchaAI. O fluxo é o mesmo, qualquer que tenha sido o método de detecção: method=turnstile, a sitekey, a URL e, se existir, o data-action.
import requests
import time
API_KEY = "YOUR_API_KEY"
def solve_detected_turnstile(detection_result):
"""Solve Turnstile using detection results."""
if not detection_result["turnstile_present"]:
raise ValueError("No Turnstile detected")
if not detection_result["sitekey"]:
raise ValueError("Sitekey not found — may need browser-based extraction")
params = {
"key": API_KEY,
"method": "turnstile",
"sitekey": detection_result["sitekey"],
"pageurl": detection_result["url"],
"json": 1,
}
# Include action if present
if detection_result.get("action"):
params["action"] = detection_result["action"]
submit = requests.post("https://ocr.captchaai.com/in.php", data=params)
task_id = submit.json()["request"]
for _ in range(60):
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("Turnstile solve timed out")
# Full workflow
detector = TurnstileDetector("https://example.com/signup")
info = detector.detect()
if info["turnstile_present"]:
token = solve_detected_turnstile(info)
print(f"Token: {token[:50]}...")
Um time de QA em São Paulo validando um cadastro em staging (região sa-east-1) segue esse fluxo: detecta o Turnstile, envia sitekey e URL, usa o token retornado — sem depender de alguém clicando no widget a cada execução.
Situações que fogem do padrão
| Cenário | Desafio | Solução |
|---|---|---|
| Sitekey em arquivo JS externo | Ausente do HTML | Parseie os arquivos JS vinculados |
| Sitekey vinda de resposta de API | Carregada após XHR | Monitore requisições de rede |
| Vários widgets de Turnstile | Sitekeys diferentes na página | Associe a sitekey ao formulário certo |
| Turnstile em shadow DOM | Seletores comuns não alcançam | Use shadowRoot.querySelector |
| Sitekey renderizada no servidor | Embutida em variáveis de template | Verifique as tags <script> |
| Turnstile atrás de autenticação | Invisível na página pública | Autentique antes de detectar |
Por que a detecção falha (e como corrigir)
| Sintoma | Causa | Correção |
|---|---|---|
| Script encontrado, sem sitekey | Config vinda de outra fonte | Verifique JS vinculados e XHR |
| Sitekey errada extraída | Vários widgets na página | Associe as sitekeys aos formulários próximos |
| Detecção funciona, resolução falha | action exigido na validação |
Inclua data-action na requisição |
cf-turnstile-response vazio |
Widget ainda carregando | Aguarde o carregamento concluir |
Perguntas frequentes
As sitekeys do Turnstile podem mudar?
Sim, a qualquer momento — extraia a sitekey direto da página em cada execução, nunca fixá-la no código.
Preciso informar o parâmetro action na resolução?
Só se o site validar isso no lado do servidor. Se data-action aparecer no HTML ou na configuração JavaScript, inclua o mesmo valor na requisição de resolução para evitar rejeições.
Posso testar os scripts sem tocar em produção?
Sim — rode a detecção contra uma URL de staging (https://staging.example.com/...) com dados fictícios antes de apontar para um ambiente real.
Quantos widgets de Turnstile cabem na mesma página?
Sem limite técnico, mas cada widget tem sua sitekey. Com mais de um — login e contato, por exemplo —, associe cada sitekey ao formulário correspondente.
Em resumo
Detectar o Turnstile envolve três verificações: tag de script, contêiner cf-turnstile com data-sitekey e chamadas turnstile.render(). Use HTML estático para integrações simples e Selenium/Puppeteer para widgets dinâmicos. Depois, resolva com o solucionador de Turnstile da CaptchaAI — todos os modos são tratados igual, com alta taxa de sucesso e resolução em menos de 10 segundos.