TurnstileTask | Cloudflare Challenge
Автоматически поддерживаются все подтипы Turnstile: manual, non-interactive и invisible. Поэтому нет необходимости указывать подтип для обычной капчи.
Ознакомьтесь со всеми тремя вариантами распознавания капчи и выберете наиболее предпочтительный для вас.
Вариант 1 (Turnstile)
Вам требуется решить обычную turstile капчу, как здесь. Обратите внимание, что капча на страницах CloudFlare может выглядеть идентично. Посмотрите в конце статьи как отличить обычный Turnstile от Cloudflare Challenge.
Параметры запроса
type
<string>requiredTurnstileTaskProxyless
websiteURL
<string>requiredАдрес страницы, на которой решается капча
websiteKey
<string>requiredКлюч Turnstile
pageAction
<string>optionalПоле action
, которое можно найти в callback функции для загрузки капчи
data
<string>optionalЗначение поля data можно взять из параметра cData
.
Вариант 2 (CloudFlare)
Вы работаете через браузер, и Вам требуется получить токен для прохождения CloudFlare
Параметры запроса
type
<string>requiredTurnstileTaskProxyless
websiteURL
<string>requiredАдрес страницы, на которой решается капча
websiteKey
<string>requiredКлюч Turnstile
cloudflareTaskType
<string>requiredtoken
pageAction
<string>requiredПоле action
, которое можно найти в callback функции для загрузки капчи. Если используется cloudflareTaskType, то action
обычно “managed“ или “non-interactive“.
userAgent
<string>requiredUser-Agent браузера.
Передавайте только актуальный UA от ОС Windows. Сейчас таковым является: userAgentPlaceholder
data
<string>requiredЗначение поля data можно взять из параметра cData
.
pageData
<string>requiredЗначение поля pageData можно взять из параметра chlPageData
.
apiJsUrl
<string>optionalСтрока, которая содержит ссылку на скрипт капчи.
Прокси для получения токена передавать не обязательно.
Эти параметры находятся в объекте, который передаётся во время создания капчи в функцию window.turnstile.render(el, paramsObj)
. Получить их можно, например, с помощью выполнения JavaScript перед загрузкой остальных скриптов:
(function () {
const obj = {
render: function () {
const { action, cData, chlPageData } = arguments[1];
const params = [
["action", action],
["data", cData],
["pageData", chlPageData],
];
console.table(params)
}
};
Object.defineProperty(window, "turnstile", {
get: () => {
return obj;
},
});
})();
При вызове window.turnstile.render(el, paramsObj)
загружается капча на странице, и при успешном решении вызывается функция callback
, которая передает информацию о решении.
window.turnstile.render(el, paramsObj):
el
: DOM-элемент для вставки в него капчи.
paramsObj
: Объект параметров, содержащий информацию о капче и инструкции для ее решения. Этот объект обычно содержит такие поля, как
sitekey, action, cData, chlPageData, callback.
callback
– функция обратного вызова после успешного прохождения капчи.
Вариант 3 (CloudFlare)
Вы работаете с помощью запросов, и Вам требуются куки cf_clearance
. Обязательно нужны ваши прокси
Параметры запроса
type
<string>requiredTurnstileTask
websiteURL
<string>requiredАдрес страницы, на которой решается капча
websiteKey
<string>requiredКлюч Turnstile(можно передать любую строку)
cloudflareTaskType
<string>optionalcf_clearance
htmlPageBase64
<string>requiredЗакодированная в base64 html страница "Just a moment", которая выдаётся с кодом 403 при обращении к сайту с данной защитой.
Пример получения строки htmlPageBase64:
var htmlContent = document.documentElement.outerHTML;
var htmlBase64 = btoa(unescape(encodeURIComponent(htmlContent)));
console.log(htmlBase64);
userAgent
<string>requiredUser-Agent браузера.
Передавайте только актуальный UA от ОС Windows. Сейчас таковым является версия: userAgentPlaceholder
proxyType
<string>requiredhttp - regular http/https proxy;
https - try this option only if "http" doesn't work (required for some custom proxies);
socks4 - socks4 proxy;
socks5 - socks5 proxy.
proxyAddress
<string>requiredIP адрес прокси IPv4/IPv6. Не допускается:
- использование имен хостов;
- использование прозрачных прокси (там, где можно видеть IP клиента);
- использование прокси на локальных машинах.
proxyPort
<integer>requiredПорт прокси.
proxyLogin
<string>requiredЛогин прокси-сервера.
proxyPassword
<string>requiredПароль прокси-сервера.
Примеры запросов
Вариант 1. Обычный Turnstile:
https://api.capmonster.cloud/createTask
Запрос
{
"clientKey":"API_KEY",
"task":
{
"type":"TurnstileTaskProxyless",
"websiteURL":"http://tsmanaged.zlsupport.com",
"websiteKey":"0x4AAAAAAABUYP0XeMJF0xoy"
}
}
Ответ
{
"errorId":0,
"taskId":407533072
}
Вариант 2. CloudFlare (token)
https://api.capmonster.cloud/createTask
Запрос
{
"clientKey": "API_KEY",
"task": {
"type": "TurnstileTask",
"websiteURL": "https://example.com",
"websiteKey": "0x4AAAAAAADnPIDROrmt1Wwj",
"cloudflareTaskType": "token",
"userAgent":"userAgentPlaceholder",
"pageAction": "managed",
"pageData": "HUHDWUHuhuwfiweh32..uh2uhuhyugYUG=",
"data": "874291f4retD1366"
}
}
Ответ
{
"errorId":0,
"taskId":407533072
}
Вариант 3. CloudFlare (cookie)
https://api.capmonster.cloud/createTask
Запрос
{
"clientKey":"API_KEY",
"task": {
"type":"TurnstileTask",
"websiteURL":"https://example.com",
"websiteKey":"xxxxxxxxxx",
"cloudflareTaskType": "cf_clearance",
"htmlPageBase64": "PCFET0NUWVBFIGh0...vYm9keT48L2h0bWw+",
"userAgent": "userAgentPlaceholder",
"proxyType":"http",
"proxyAddress":"8.8.8.8",
"proxyPort":8080,
"proxyLogin":"proxyLoginHere",
"proxyPassword":"proxyPasswordHere"
}
}
Ответ
{
"errorId":0,
"taskId":407533072
}
Метод получения результата задачи
Используйте метод getTaskResult, чтобы получить решение Turnstile. В зависимости от загрузки системы вы получите ответ через время в диапазоне от 5 до 20 с.
Свойство | Тип | Описание |
---|---|---|
cf_clearance | String | Специальные куки cloudflare, которые вы можете подставить в свой браузер |
token | String | Используйте токен при вызове callback функции |
Как отличить обычный Turnstile от Cloudflare Challenge.
Cloudflare challenge может выглядеть по-разному.
Обычный вариант:
Стилизованные варианты:
Чтобы окончательно убедиться в наличии Cloudflare, можно открыть инструменты разработчика, посмотреть трафик, изучить код страницы и увидеть характерные признаки:
- Первый запрос к сайту возвращает код 403:
- Форма с id challenge-form имеет атрибут action (не путать с action из параметров для капчи turnstile), содержащий параметр
__cf_chl_f_tk=
:
- На странице находится два похожих тега
<script>
, которые создают новое значение в объектеwindow
:
Пример реализации решения с помощью Selenium на Node.js
const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
(async function example() {
const options = new chrome.Options();
options.addArguments('--auto-open-devtools-for-tabs')
const driver = new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
try {
driver.executeScript(`
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
let p = {
type: "TurnstileTaskProxyless",
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent
}
console.log(JSON.stringify(p))
window.params = p;
window.turnstileCallback = b.callback;
return target.render.apply(this, arguments);
}
}
return target[prop];
}
});
`)
driver.get('SITE WITH CAPTCHA');
const params = await driver.executeScript(`
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(window.params)
}, 2000)
})
`);
if (params) {
const data = {
clientKey: 'API KEY',
task: {
type: 'TurnstileTaskProxyless',
websiteURL: params.websiteURL,
websiteKey: params.websiteKey,
data: params.data,
action: params.action
}
}
const createResult = await fetch('https://api.capmonster.cloud/createTask', {
method: 'post',
body: JSON.stringify(data)
});
const createTaskResult = await createResult.json()
if (createTaskResult.taskId) {
const asyncDelay = (timeout) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
}, timeout);
});
const getTaskResult = async (taskId) => {
const taskResult = await fetch('https://api.capmonster.cloud/getTaskResult', {
method: 'post',
body: JSON.stringify({
"clientKey":"API KEY",
"taskId": createTaskResult.taskId
})
});
const taskResponse = await taskResult.json();
if (taskResponse.status === 'processing') {
await asyncDelay(5000);
return await getTaskResult(taskId)
}
return taskResponse;
}
const taskRes = await getTaskResult(createTaskResult.taskId)
if (taskRes.solution) {
await driver.executeScript(`
window.turnstileCallback(${taskRes.solution.token});
`);
}
}
}
//DO SOMETHING
} finally {
await driver.quit();
}
})();
Как найти все нужные параметры для создания задачи на решение
Вручную
- Откройте ваш сайт, где отображается капча, в браузере.
- Правой кнопкой кликните по элементу капчи и выберите Inspect.
Вариант 1.
websiteKey
Можно найти в Элементах:
Также можно использовать команду в консоли, открыв url капчи, начинающегося с: https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/g… в отдельной вкладке:
console.log(window._cf_chl_opt.chlApiSitekey);
chlApiSitekey – это и есть sitekey.
pageAction
Action и также sitekey можно найти в callback-функции:
Параметры для вариантов 2 и 3 лучше извлекать автоматически:
Автоматически
Удобный способ автоматизировать поиск всех необходимых параметров. Некоторые параметры генерируются заново при каждой загрузке страницы, поэтому для их извлечения потребуется работать через браузер – обычный или в режиме headless (например, с помощью Playwright). Так как значения динамических параметров хранятся недолго, капчу нужно решать сразу после их получения.
Приведённые фрагменты кода являются базовыми примерами для ознакомления в извлечении необходимых параметров. Точная реализация будет зависеть от вашего сайта с капчей, его структуры и используемых HTML-элементов и селекторов.
- JavaScript
- Python
- C#
Вариант 1 (в браузере)
// Функция для проверки наличия window.onloadTurnstileCallback
const checkTurnstileCallback = () => {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject('Таймаут ожидания callback'), 30000);
const interval = setInterval(() => {
if (window.onloadTurnstileCallback !== undefined) {
clearInterval(interval);
clearTimeout(timeout);
const callbackDetails = window.onloadTurnstileCallback.toString();
const sitekeyMatch = callbackDetails.match(/sitekey: ['"]([^'"]+)['"]/);
const actionMatch = callbackDetails.match(/action: ['"]([^'"]+)['"]/);
resolve({
sitekey: sitekeyMatch ? sitekeyMatch[1] : null,
action: actionMatch ? actionMatch[1] : null,
});
}
}, 500);
});
};
// Попытка найти любой элемент с data-sitekey
const turnstileElement = document.querySelector('[data-sitekey]');
if (turnstileElement) {
const sitekey = turnstileElement.getAttribute("data-sitekey");
console.log("Turnstile Sitekey (из элемента):", sitekey);
} else {
console.log("Turnstile элемент не найден. Проверяем через callback...");
checkTurnstileCallback()
.then((data) => {
console.log("Turnstile Params (из callback):", data);
})
.catch((error) => {
console.error(error);
});
}
Вариант 2 (Node.js)
import { chromium } from "playwright";
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
let params = null;
try {
while (!params) {
await page.goto("https://example.com");
await page.evaluate(() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === "render") {
return function (a, b) {
const p = {
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent,
};
window.params = p;
return target.render.apply(this, arguments);
};
}
return target[prop];
},
});
});
params = await page.evaluate(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(window.params || null), 5000);
});
});
if (!params) {
await page.waitForTimeout(3000);
}
}
console.log("Turnstile Params:", params);
} finally {
await browser.close();
}
})();
Вариант 3 (Node.js)
import { chromium } from "playwright";
import { Buffer } from "buffer";
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
let websiteKey = null;
while (!websiteKey) {
await page.goto("https://example.com");
await page.evaluate(() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === "render") {
return function (a, b) {
window.websiteKey = b.sitekey;
return target.render.apply(this, arguments);
};
}
return target[prop];
},
});
});
websiteKey = await page.evaluate(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(window.websiteKey || null), 5000);
});
});
if (!websiteKey) {
await page.waitForTimeout(3000);
}
}
const html = await page.content();
const htmlPageBase64 = Buffer.from(html).toString("base64");
const result = {
websiteKey,
htmlPageBase64,
};
console.log(result);
await browser.close();
})();
Вариант 1
import asyncio
from playwright.async_api import async_playwright
async def run():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
context = await browser.new_context()
page = await context.new_page()
await page.goto("https://example.com")
element = await page.query_selector('[data-sitekey]')
if element:
sitekey = await element.get_attribute("data-sitekey")
print("Turnstile Sitekey (из элемента):", sitekey)
else:
print("Turnstile элемент не найден. Проверяем через callback...")
try:
result = await page.evaluate('''() => {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject('Таймаут ожидания callback'), 30000);
const interval = setInterval(() => {
if (window.onloadTurnstileCallback !== undefined) {
clearInterval(interval);
clearTimeout(timeout);
const cbStr = window.onloadTurnstileCallback.toString();
const sitekeyMatch = cbStr.match(/sitekey: ['"]([^'"]+)['"]/);
const actionMatch = cbStr.match(/action: ['"]([^'"]+)['"]/);
resolve({
sitekey: sitekeyMatch ? sitekeyMatch[1] : null,
action: actionMatch ? actionMatch[1] : null,
});
}
}, 500);
});
}''')
print("Turnstile Params (из callback):", result)
except Exception as e:
print("Ошибка:", e)
await browser.close()
asyncio.run(run())
Вариант 2
import asyncio
from playwright.async_api import async_playwright
async def extract_turnstile_params():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
params = None
while not params:
await page.goto("https://example.com")
await page.evaluate("""
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === "render") {
return function(a, b) {
const p = {
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent
};
window.params = p;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
""")
await page.wait_for_timeout(5000)
params = await page.evaluate("window.params || null")
if not params:
await page.wait_for_timeout(3000)
print("Turnstile Params:", params)
await browser.close()
asyncio.run(extract_turnstile_params())
Вариант 3
import asyncio
import base64
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
website_key = None
while not website_key:
await page.goto("https://example.com")
await page.evaluate("""
() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
window.websiteKey = b.sitekey;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
}
""")
website_key = await page.evaluate("""
() => new Promise(resolve => {
setTimeout(() => resolve(window.websiteKey || null), 5000);
})
""")
if not website_key:
await page.wait_for_timeout(3000)
html = await page.content()
html_base64 = base64.b64encode(html.encode("utf-8")).decode("utf-8")
result = {
"websiteKey": website_key,
"htmlPageBase64": html_base64
}
print(result)
await browser.close()
asyncio.run(main())
Вариант 1
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Playwright;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false
});
var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await page.GotoAsync("https://example.com");
var element = await page.QuerySelectorAsync("[data-sitekey]");
if (element != null)
{
var sitekey = await element.GetAttributeAsync("data-sitekey");
Console.WriteLine($"Turnstile Sitekey (из элемента): {sitekey}");
}
else
{
Console.WriteLine("Turnstile элемент не найден. Проверяем через callback...");
try
{
var result = await page.EvaluateAsync(@"() => {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject('Таймаут ожидания callback'), 30000);
const interval = setInterval(() => {
if (window.onloadTurnstileCallback !== undefined) {
clearInterval(interval);
clearTimeout(timeout);
const cbStr = window.onloadTurnstileCallback.toString();
const sitekeyMatch = cbStr.match(/sitekey: ['""]([^'""]+)['""]/);
const actionMatch = cbStr.match(/action: ['""]([^'""]+)['""]/);
resolve({
sitekey: sitekeyMatch ? sitekeyMatch[1] : null,
action: actionMatch ? actionMatch[1] : null
});
}
}, 500);
});
}");
Console.WriteLine("Turnstile Params (из callback): " + result?.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Ошибка: " + ex.Message);
}
}
await browser.CloseAsync();
}
}
Вариант 2
using Microsoft.Playwright;
using System.Text.Json;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false
});
var page = await browser.NewPageAsync();
object? parameters = null;
while (parameters == null)
{
await page.GotoAsync("https://example.com");
await page.EvaluateAsync(@"() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
const p = {
websiteKey: b.sitekey,
websiteURL: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent
};
window.params = p;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
}");
parameters = await page.EvaluateAsync(@"() => new Promise(resolve => {
setTimeout(() => resolve(window.params || null), 5000);
})");
if (parameters == null)
{
await page.WaitForTimeoutAsync(3000);
}
}
Console.WriteLine("Turnstile Params:");
Console.WriteLine(JsonSerializer.Serialize(parameters, new JsonSerializerOptions { WriteIndented = true }));
await browser.CloseAsync();
}
}
Вариант 3
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Playwright;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(
new BrowserTypeLaunchOptions { Headless = false });
var page = await browser.NewPageAsync();
string websiteKey = null;
while (websiteKey == null)
{
await page.GotoAsync("https://example.com");
await page.EvaluateAsync(@"() => {
window.turnstile = new Proxy(window.turnstile, {
get(target, prop) {
if (prop === 'render') {
return function(a, b) {
window.websiteKey = b.sitekey;
return target.render.apply(this, arguments);
};
}
return target[prop];
}
});
}");
websiteKey = await page.EvaluateAsync<string>(@"() =>
new Promise(resolve => {
setTimeout(() => resolve(window.websiteKey || null), 5000);
})");
if (websiteKey == null)
{
await page.WaitForTimeoutAsync(3000);
}
}
var html = await page.ContentAsync();
var htmlBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(html));
Console.WriteLine($"websiteKey: {websiteKey}");
Console.WriteLine($"htmlPageBase64: {htmlBase64}");
await browser.CloseAsync();
}
}
Используйте библиотеку SDK
- JavaScript
- Python
- C#
// https://github.com/ZennoLab/capmonstercloud-client-js
import { CapMonsterCloudClientFactory, ClientOptions, TurnstileRequest } from '@zennolab_com/capmonstercloud-client';
document.addEventListener('DOMContentLoaded', async () => {
const cmcClient = CapMonsterCloudClientFactory.Create(new ClientOptions({ clientKey: '<your capmonster.cloud API key>' }));
console.log(await cmcClient.getBalance());
const turnstileRequest = new TurnstileRequest({
websiteURL: 'https://tsinvisble.zlsupport.com',
websiteKey: '0x4AAAAAAABUY0VLtOUMAHxE',
cloudflareTaskType: 'cf_clearance',
proxyType: 'http',
proxyAddress: '8.8.8.8',
proxyPort: 8080,
proxyLogin: 'proxyLoginHere',
proxyPassword: 'proxyPasswordHere',
pageData: 'pageDataHere',
data: 'dataHere',
htmlPageBase64: 'htmlPageBase64Here',
userAgent: 'userAgentHere',
});
console.log(await cmcClient.Solve(turnstileRequest));
});
# https://github.com/ZennoLab/capmonstercloud-client-python
# Cloudflare Turnstile:
import asyncio
from capmonstercloudclient import CapMonsterClient, ClientOptions
from capmonstercloudclient.requests import TurnstileRequest
client_options = ClientOptions(api_key="your_api_key") # Replace with your CapMonsterCloud API key
cap_monster_client = CapMonsterClient(options=client_options)
turnstile_request = TurnstileRequest(
websiteURL="http://tsmanaged.zlsupport.com", # Replace with the URL of the page with the captcha
websiteKey="0x4AAAAAAABUYP0XeMJF0xoy" # Replace with the website key for the captcha
)
async def solve_captcha():
return await cap_monster_client.solve_captcha(turnstile_request)
responses = asyncio.run(solve_captcha())
print(responses)
# Cloudflare Challenge (token)
import asyncio
from capmonstercloudclient import CapMonsterClient, ClientOptions
from capmonstercloudclient.requests import TurnstileProxylessRequest
client_options = ClientOptions(api_key="your_api_key") # Replace with your CapMonsterCloud API key
cap_monster_client = CapMonsterClient(options=client_options)
turnstile_request = TurnstileProxylessRequest(
websiteURL="https://example.com", # Replace with the URL of the page with the captcha
websiteKey="0x4AAAAAAABUYP0XeMJF0xoy", # Replace with the website key for the captcha
data="YOUR_DATA_HERE",
pageAction="managed",
cloudflareTaskType="token",
pageData="YOUR_PAGE_DATA_HERE",
userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36" # Use the current userAgent
)
async def solve_captcha():
return await cap_monster_client.solve_captcha(turnstile_request)
responses = asyncio.run(solve_captcha())
print(responses)
# Cloudflare Challenge (cookie cf_clearance)
import asyncio
from capmonstercloudclient import CapMonsterClient, ClientOptions
from capmonstercloudclient.requests import TurnstileRequest
client_options = ClientOptions(api_key="your_api_key") # Replace with your CapMonsterCloud API key
cap_monster_client = CapMonsterClient(options=client_options)
turnstile_request = TurnstileRequest(
websiteURL="https://example.com", # Replace with the URL of the page with the captcha
websiteKey="0x4AAAAAAABUYP0XeMJF0xoy", # Replace with the website key for the captcha
cloudflareTaskType="cf_clearance",
userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", # Use the current userAgent
htmlPageBase64="htmlPageBase64Here",
proxyType="http", # Type of proxy (http, https, socks4, socks5)
proxyAddress="8.8.8.8",
proxyPort=8000,
proxyLogin="proxyLoginHere",
proxyPassword="proxyPasswordHere"
)
async def solve_captcha():
return await cap_monster_client.solve_captcha(turnstile_request)
responses = asyncio.run(solve_captcha())
print(responses)
// https://github.com/ZennoLab/capmonstercloud-client-dotnet
// Cloudflare Turnstile:
using Zennolab.CapMonsterCloud.Requests;
using Zennolab.CapMonsterCloud;
class Program
{
static async Task Main(string[] args)
{
var clientOptions = new ClientOptions
{
ClientKey = "your_api_key" // Replace with your CapMonster Cloud API key
};
var cmCloudClient = CapMonsterCloudClientFactory.Create(clientOptions);
var turnstileRequest = new TurnstileProxylessRequest
{
WebsiteUrl = "http://tsmanaged.zlsupport.com", // Replace with the URL of the page with the captcha
WebsiteKey = "0x4AAAAAAABUYP0XeMJF0xoy" // Replace with the website key for the captcha
};
var turnstileResult = await cmCloudClient.SolveAsync(turnstileRequest);
Console.WriteLine("Captcha Solution: " + turnstileResult.Solution.Value);
}
}
// Cloudflare Challenge (token):
using Zennolab.CapMonsterCloud.Requests;
using Zennolab.CapMonsterCloud;
class Program
{
static async Task Main(string[] args)
{
var clientOptions = new ClientOptions
{
ClientKey = "your_api_key" // Replace with your CapMonster Cloud API key
};
var cmCloudClient = CapMonsterCloudClientFactory.Create(clientOptions);
var turnstileRequest = new TurnstileProxylessRequest
{
WebsiteUrl = "https://example.com", // Replace with the URL of the page with the captcha
WebsiteKey = "0x4AAAAAAABUYP0XeMJF0xoy", // Replace with the website key for the captcha
Data = "data_here",
PageAction = "managed",
CloudflareTaskType = "token",
PageData = "pagedata_here",
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36" // Use the current UserAgent
};
var turnstileResult = await cmCloudClient.SolveAsync(turnstileRequest);
Console.WriteLine("Captcha Solution: " + turnstileResult.Solution.Value);
}
}
// Cloudflare Challenge (cookie cf_clearance):
using Zennolab.CapMonsterCloud.Requests;
using Zennolab.CapMonsterCloud;
class Program
{
static async Task Main(string[] args)
{
var clientOptions = new ClientOptions
{
ClientKey = "your_api_key" // Replace with your CapMonster Cloud API key
};
var cmCloudClient = CapMonsterCloudClientFactory.Create(clientOptions);
var turnstileRequest = new TurnstileRequest
{
WebsiteUrl = "https://example.com", // URL with Turnstile challenge
WebsiteKey = "0x4AAAAAAADnPIDROrmt1Wwj", // Replace with the correct website key
CloudflareTaskType = "cf_clearance",
ProxyType = ProxyType.Http, // Replace with the required type
ProxyAddress = "8.8.8.8",
ProxyPort = 8000,
ProxyLogin = "proxyLoginHere",
ProxyPassword = "proxyPasswordHere",
PageData = "pageDataHere",
Data = "pageDataHere",
HtmlPageBase64 = "htmlPageBase64Here",
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36" // Use an up-to-date userAgent
};
var turnstileResult = await cmCloudClient.SolveAsync(turnstileRequest);
Console.WriteLine("Captcha Solved. cf_clearance cookie: " + turnstileResult.Solution.Clearance);
}
}