自动绕过 Cloudflare 验证码 - 两条相反的方法(选择最适合您的方法)

1. 了解Cloudflare验证码

Cloudflare turnstile验证码有2种类型:

  • 独立Cloudflare Trunstile验证码:验证码小部件放在网站页面上,保护表单免受自动提交影响。参见此示例。
  • Cloudflare Turnstile挑战页面:网站上的验证码通过Cloudflare代理。参见此示例

2. 旁路技术

2.1. 免费(仅限Python):

python 复制代码
import undetected_chromedriver as uc

driver = uc.Chrome(headless=True,use_subprocess=False)
driver.get('https://rucaptcha.com/42')
driver.save_screenshot('captcha.png')
csharp 复制代码
from DrissionPage import ChromiumPage

page = ChromiumPage()
page.get('https://rucaptcha.com/42')

2.2. 使用2Captcha付费旁路:

它是如何工作的?

向2Captcha发送API以接收cf-turnstile-response令牌。他们的工作人员将手动绕过这个验证码,并将cf-turnstile-response令牌发回给我们。最后,通过设置cf-turnstile-response输入的值,使用此令牌绕过Cloudflare。

2.2.1. 独立Turnstile验证码

步骤1:向2Captcha发送turnstile旁路请求,内容如下:

json 复制代码
{
  "key": "YOUR_API_KEY", // Go to https://2captcha.com/enterpage and copy your API key and paste it here
  "method": "turnstile",
  "sitekey": "0x4AAAAAAAC3DHQFLr1GavRN", // Each website using an unique sitekey
  "pageurl": "https://2captcha.com/demo/cloudflare-turnstile", // Your website url using CF turnstile
  "json": 1
}
  • **如何获取站点密钥值?**您可以从CF iframe标签中src属性获取值。请参阅以下详细信息:
  • 响应示例:
vbscript 复制代码
{

  "status": 1,

  "request": "2122988149" // request Id to get bypass token

}

第2步:等待10秒钟

  • 步骤1中的请求会触发一项手动绕过Cloudflare的作业。因此,处理作业需要7-10秒。你需要等待。

步骤3:发送一个GET请求来接收cf-turnstile-response令牌

json 复制代码
{

  "status": 1,

  "request": "0.WoGeDojxQzHCCk023JRjfxv23olYh37jFdvPrcqmNeQ7PbSYIEuiBTK2SR_GdjfMitYEC23Gm7Vt93U1CPcI6aIFEhG-ffe1i9e6tIfIlYCFtb7OMxTB4tKCyTdpiaA.SP5YT77nuMNdOhZlvoBWAQ.da6448d22df7dd92f56a9fcf6d7138e5ee712bcf7d00c281f419b3bc091cbe64"

}

步骤4:在开发工具的控制台选项卡上设置cf-turnstile-response输入的值。

ini 复制代码
document.querySelector('[name="cf-turnstile-response"]').value = 'TOKEN';

第5步:验证码被绕过。继续你的工作。

您可以在此处查看独立turnstile验证码的最新指南。如果您正在寻找2Captcha的C#、PHP、Ruby、Java、Python或Javascript的验证码代码示例,请访问他们的git存储库

2.2.2. Cloudflare挑战页面

使用puppeteer JS进行旁路

  • 首先,发送与独立turnstile验证码 相同的POST 请求来触发2Captcha 旁路作业。但是,还有3 个必填字段需要设置,包括数据、页面数据和操作
makefile 复制代码
Endpoint: https://2captcha.com/in.php

Method: POST



{

	"key": "YOUR_API_KEY",

	"method": "turnstile",

	"sitekey": "0x0AAAAAAADnPIDROzbs0Aaj",

	"data": "7fab0000b0e0ff00",

	"pagedata": "3gAFo2...0ME1UVT0=",

	"pageurl": "https://2captcha.com/",

	"action": "managed",

	"json": 1

}
  • **我们如何获取这些字段的值?**在加载Turnstile小部件之前,您应该通过注入以下JavaScript来拦截window .turnstile.render调用。
javascript 复制代码
// This file is named inject.js

console.clear = () => console.log('Console was cleared')

const i = setInterval(() => {

    if (window.turnstile) {

        clearInterval(i)

        window.turnstile.render = (a, b) => {

            let params = {

                sitekey: b.sitekey,

                pageurl: window.location.href,

                data: b.cData,

                pagedata: b.chlPageData,

                action: b.action,

                userAgent: navigator.userAgent,

                json: 1

            }

            // we will intercept the message in puppeeter

            console.log('intercepted-params:' + JSON.stringify(params))

            window.cfCallback = b.callback

            return

        }

    }

}, 50)
  • 在Puppeteer中,每当加载新文档时,使用Page.evaluateOnNewDocument(inject_script)方法注入脚本。将上面的JS脚本存储在名为inject.js的文件中,要绕过的脚本则为:
javascript 复制代码
import { launch } from 'puppeteer'

import { Solver } from '@2captcha/captcha-solver'

import { readFileSync } from 'fs'



const solver = new Solver(`API_KEY`) // Set your API key here



const example = async () => {

    const browser = await launch({

        headless: false,

        devtools: true

    })

    const [page] = await browser.pages()

		// Load inject.js content

    const preloadFile = readFileSync('./inject.js', 'utf8');

    await page.evaluateOnNewDocument(preloadFile);



    // Here we intercept the console messages to catch the message logged by inject.js script

    page.on('console', async (msg) => {

        const txt = msg.text()

        if (txt.includes('intercepted-params:')) {

            const params = JSON.parse(txt.replace('intercepted-params:', ''))

            console.log(params)



            try {

                console.log(`Solving the captcha...`)

                const res = await solver.cloudflareTurnstile(params)

                console.log(`Solved the captcha ${res.id}`)

                console.log(res)

                await page.evaluate((token) => {

                    cfCallback(token)

                }, res.data)

            } catch (e) {

                console.log(e.err)

                return process.exit()

            }

        } else {

            return;

        }

    })

		// When the page is redirected, there is a log "intercepted-params: ..." in the browser console

    page.goto('https://rucaptcha.com/42')

}

example() // Run the example function above

使用Selenium C#进行旁路

  • C#只是一个实施例。。2Captcha能够以任何其他语言执行。
  • 在Selenium中,使用和Puppeteer相同的方式。调用Chrome开发工具的命令Page.addScriptToEvaluateOnNewDocument以注入脚本,而非page.evaluateOnNewDocument();。
csharp 复制代码
string injectedScripts = File.ReadAllText("inject.js", Encoding.UTF8);

((ChromeDriver)AtataContext.Current.Driver)

    .ExecuteCdpCommand("Page.addScriptToEvaluateOnNewDocument",

    new System.Collections.Generic.Dictionary<string, object> { { "source", injectedScripts } }

);
  • 加载包含文本"intercepted-params"的消息。不要忘记在所有级别设置日志首选项以接收chromeOptions.SetLoggingPreference(LogType.Browser, OpenQA.Selenium.LogLevel.All)的日志;
scss 复制代码
// Get the message logged by the inject.js for 2captcha params
LogEntry message = AtataContext.Current.Driver.Manage().Logs.GetLog(LogType.Browser).FirstOrDefault(m => m.Message.Contains("intercepted-params:"));
  • 将参数处理至Turnstile验证码请求中以获取数据、页面数据和操作。最后,使用js脚本*$"cfCallback(' {token}' );"绕过令牌回调的Cloudflare*验证。
erlang 复制代码
if (message != null)

{

    string paramString = Regex.Replace(message.Message, @".*intercepted-params:", "")

        .Replace("}\"", "}")

        .Replace("\\", "");

    TwoCaptchaParams param = JsonConvert.DeserializeObject<TwoCaptchaParams>(@$"{paramString}");



    // Solve the CAPTCHA using 2captcha-csharp

    CustomTwoCaptcha solver = new CustomTwoCaptcha(_apiKey);



    TurnstileChallengePage captcha = new TurnstileChallengePage();

    captcha.SetSiteKey(param.SiteKey);

    captcha.SetUrl(param.PageUrl);

    captcha.SetData(param.Data);

    captcha.SetPageData(param.PageData);

    captcha.SetAction(param.Action);

    captcha.SetUserAgent(param.UserAgent);



    var captchaId = solver.SendRequest(captcha).GetAwaiter().GetResult();

    Thread.Sleep(10);

    string token = solver.GetResult(captchaId).GetAwaiter().GetResult();

    // Inject the solved CAPTCHA token

    AtataContext.Current.Driver.AsScriptExecutor().ExecuteScript($"cfCallback('{token}');");

}

else

{

    Console.WriteLine("Console message not found.");

}
  • 最后,执行运行,您将成功绕过CloudFlare。祝贺!

3. 总结

以自动化方式绕过Cloudflare验证码需要对安全措施带来的不同类型的挑战有细致入微的了解。在这种情况下,2captcha应运成为一种可靠且可持续的解决方案。

值得注意的是,应该负责任地、合乎道德地使用自动化旁路技术。我希望这个话题对你有益!

4. 引用

2Captcha指南:https://2captcha.com/blog/bypass-cloudflare-turnstile-captcha

相关推荐
yngsqq3 分钟前
031集——文本文件按空格分行——C#学习笔记
笔记·学习·c#
_.Switch10 分钟前
Python机器学习模型的部署与维护:版本管理、监控与更新策略
开发语言·人工智能·python·算法·机器学习
Hoper.J29 分钟前
PyTorch 模型保存与加载的三种常用方式
人工智能·pytorch·python
弱冠少年1 小时前
websockets库使用(基于Python)
开发语言·python·numpy
技术无疆2 小时前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
羊小猪~~2 小时前
机器学习/数据分析--用通俗语言讲解时间序列自回归(AR)模型,并用其预测天气,拟合度98%+
人工智能·python·机器学习·数据挖掘·数据分析·回归·时序数据库
qq_273900232 小时前
解析TMalign文本文件中的转换矩阵
python·生物信息学
阿华的代码王国3 小时前
【JavaEE】——文件IO的应用
开发语言·python
电饭叔3 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
程序猿小D4 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa