cloudflare-turnstile-solver README

The project's README from github.com/biusberline/cloudflare-turnstile-solver. As one markdown file: README.md.

Peak - solve Cloudflare Turnstile & the 5s challenge in ~1s

Cloudflare Turnstile Solver — Get a Turnstile Token in Python

The Cloudflare Turnstile Solver package makes it easy to work with Cloudflare Turnstile from Python: it finds the Turnstile sitekey on any page, creates a valid Turnstile token via the Peak API, and hands you a cf-turnstile-response token you can inject into a form or request. It is a small, dependency-free library plus a CLI — designed for CI pipelines, QA automation, and integration engineering.

Table of Contents:

What this package does

Cloudflare Turnstile protects pages with a widget that issues a token. Two things are always needed: find the sitekey the page is using, and create a token for that sitekey. This package provides both:

  1. find_sitekey() — scan a page for its data-sitekey.
  2. create_token() — submit a solve task to the Peak API and get a valid token.
  3. token_for_page() — do both in one call.

It has no browser dependency. A single Python file, standard library only, works on headless servers and CI runners.

Quick start

$ export PEAK_API_KEY=pk_your_api_key
$ python -m cloudflare_turnstile_solver --url https://example.com/
0.AgAAABBqzz...

Or find the sitekey first, then create the token:

from cloudflare_turnstile_solver import find_sitekey, create_token

sitekey = find_sitekey("https://example.com/")
token = create_token("pk_...", sitekey, "https://example.com/")
print(token)  # -> "0.AgAAABBqzz..."

Finding a Turnstile sitekey

Turnstile widgets expose the sitekey in the markup:

<div class="cf-turnstile" data-sitekey="0x4AAAAAAAxxxx"></div>

find_sitekey() reads it for you:

from cloudflare_turnstile_solver import find_sitekey

sitekey = find_sitekey("https://example.com/")
print(sitekey)  # -> "0x4AAAAAAAxxxx"

It also finds data-action when present, so tokens are scoped correctly.

Creating a Turnstile token

A token is tied to the sitekey, the page URL, and optionally the action. To create one with the Peak API:

from cloudflare_turnstile_solver import create_token

result = create_token("pk_...", "0x4AAAAAAAxxxx", "https://example.com/",
                      proxy="http://u:[email protected]:8080")
print(result.token)

Submit the returned token as cf-turnstile-response:

cf-turnstile-response: 0.AgAAABBqzz...

⚠️ If the token is rejected, check the basics. The token is bound to the page URL and environment that created it. Use the same proxy and a matching user agent for the request.

Python API reference

Function Description
find_sitekey(url, html=None) Scan a page for its Turnstile sitekey.
find_action(html) Find an optional data-action value.
create_token(api_key, sitekey, url, proxy=None, action=None, cdata=None, ...) Create a valid token via the Peak API.
token_for_page(api_key, url, proxy=None, html=None) Find the sitekey and create a token in one call.

All functions raise TurnstileTokenError on failure. create_token retries transient failures automatically.

CLI usage

$ python -m cloudflare_turnstile_solver --url https://example.com/ --output json
{
  "sitekey": "0x4AAAAAAAxxxx",
  "token": "0.AgAAABBqzz...",
  "success": true
}

Flags: --url (required), --sitekey, --proxy, --api-key, --output {text,json}, --retries.

Examples

In a script with requests

import requests
from cloudflare_turnstile_solver import token_for_page

result = token_for_page("pk_...", "https://example.com/")
resp = requests.post("https://example.com/submit",
                     data={"cf-turnstile-response": result.token})
print(resp.status_code)

In CI / shell

TOKEN=$(python -m cloudflare_turnstile_solver --url https://example.com/)
curl -X POST https://example.com/submit \
  -H "cf-turnstile-response: $TOKEN" \
  -d "payload=..."

Powered by Peak

This package uses Peak to solve Turnstile.

Get your free API key • Docs • Pricing

FAQ

Does it run headless / without a browser?

Yes. The whole package is a single Python file on the standard library - no browser, no webdriver, no Node. It runs the same on a headless CI runner as it does locally.

How do I use a proxy?

Pass it to create_token / token_for_page with the proxy argument, or use --proxy on the CLI:

$ python -m cloudflare_turnstile_solver --url https://example.com/ --proxy http://u:[email protected]:8080

Can I use it for multiple pages on the same site?

Yes - call token_for_page per page URL. Each token is bound to the page URL it was created for, so don't reuse one token across different pages.

License

MIT

cloudflare-turnstile-solver (biusberline/cloudflare-turnstile-solver)

Searching Database…

Что это такое?Небольшая Python-библиотека и CLI для Cloudflare Turnstile на ваших страницах: она извлекает sitekey со страницы, получает валидный токен через Peak API и выдаёт вам cf-turnstile-response, который можно подставить в форму или запрос.
Это Python-библиотека или утилита командной строки?И то и другое — можно импортировать как Python-библиотеку или запустить встроенный CLI, и в обоих случаях указать страницу, с которой вы работаете. Само решение капчи выполняет сервис Peak API.
Как начать получать токены для своей страницы?Ничего устанавливать не нужно, кроме самого Python — это один файл на стандартной библиотеке. Получите ключ Peak API, затем вызовите tokenforpage(api_key, url) или запустите CLI с флагами --url и --api-key (для CI ещё есть --proxy, --output json и --retries).
Нужен ли браузер или webdriver для работы?Только Python — без браузера, webdriver и Node. Пакет представляет собой один файл на стандартной библиотеке, поэтому одинаково работает и на headless CI-раннере, и локально; для решения капчи нужен ключ Peak API.
Почему токен могут отклонить или он может перестать работать?Токены привязаны к своему окружению: каждый действует только для той страницы, для которой создан, поэтому вызывайте tokenforpage для каждой страницы отдельно, а не переиспользуйте один. Отклонённый токен обычно означает, что прокси или user agent не совпали.
Какие основные функции есть в Python API?Всё решают три вызова: findsitekey() ищет на странице data-sitekey, createtoken() отправляет задачу на решение в Peak API, а tokenforpage() делает и то и другое за один вызов. При сбоях возникает исключение TurnstileTokenError, а временные ошибки автоматически повторяются.
Это бесплатно?Сама библиотека распространяется по лицензии MIT и бесплатна. Решение капчи идёт через Peak API: на старте 1 000 бесплатных решений без привязки карты, дальше от $0.8 за 1 000 успешных решений, каждое занимает около секунды.
Можно ли пускать решение через прокси?Да — передайте его в аргументе proxy в createtoken() или tokenforpage(), либо укажите --proxy в CLI, если токен должен быть создан из той же сетевой среды.
Size
0.5 MB
Stars
346
Updated
CommitOct 12
Age
1mo
Commits · 90 Days