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

1. 简介

自动化测试是持续集成的一个关键方面,在处理验证码等安全措施时经常会遇到挑战。对持续和重复测试运行的需求可能会触发安全机制,如Cloudflare验证码,从而导致测试失败。虽然有可能在测试执行期间禁用验证码,但在某些情况下这可能并不可行。在这篇博客文章中,我们深入探讨了Cloudflare验证码的世界,重点关注独立Cloudflare Turnstile验证码和Cloudflare Turnstile挑战页面。我们将探索这些验证码的复杂性,并讨论以自动化方式绕过它们的两种有效方法。

2. 了解Cloudflare验证码

- Cloudflare turnstile验证码有2种类型:
  - 独立Cloudflare Trunstile验证码:验证码小部件放在网站页面上,保护表单免受自动提交影响。[参见此示例。](https://2captcha.com/demo/cloudflare-turnstile)
  - Cloudflare Turnstile挑战页面:网站上的验证码通过Cloudflare代理。[参见此示例](https://rucaptcha.com/42)。

3. 旁路技术

3.1. 免费(仅限Python):

- [未检测到的Chrome驱动程序](https://github.com/ultrafunkamsterdam/undetected-chromedriver):利用未检测到的Chrome浏览器允许自动化脚本与网站进行交互,而不会触发Cloudflare的安全检查。然而,该库仍然被最新的Cloudflare算法检测到。
  - [请在此处查看Python的示例文件](https://github.com/ultrafunkamsterdam/undetected-chromedriver/blob/master/example/test_workflow.py)。

```
import undetected_chromedriver as uc

driver = uc.Chrome(headless=True,use_subprocess=False)
driver.get('https://rucaptcha.com/42')
driver.save_screenshot('captcha.png')
```

- [DrissionPage](https://github.com/g1879/DrissionPage):DrissionPage是一个Python库,能够自动进行浏览器交互,可用于在不被检测的情况下浏览受Cloudflare保护的网站。
- [请在此处查看DrissionPage文档](https://g1879.gitee.io/drissionpagedocs/SessionPge/introduction/)。

```
from DrissionPage import ChromiumPage

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

3.2. 使用2Captcha付费旁路:

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

3.2.1. 独立Turnstile验证码

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

- 端点:[https://2captcha.com/in.php](https://2captcha.com/in.php**)
- 方法:**POST**
- 请求正文为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属性获取值。请参阅以下详细信息:

![](https://i0.wp.com/blog.nashtechglobal.com/wp-content/uploads/2024/01/Get-site-key-1.png?resize=1024%2C375&ssl=1)

- 响应示例:

```
{

  "status": 1,

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

}
```

第2步:等待10秒钟

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

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

- 端点:https://2captcha.com/res.php?key=YOUR_API_KEY&action=get&id=2122988149&json=1
- 响应示例:

```
{

  "status": 1,

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

}
```

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

```
document.querySelector('[name="cf-turnstile-response"]').value = 'TOKEN';
```

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

您可以在[此处](https://2captcha.com/vi/demo/cloudflare-turnstile)查看独立turnstile验证码的最新指南。如果您正在寻找2Captcha的C#、PHP、Ruby、Java、Python或Javascript的验证码代码示例,请访问[他们的git存储库](https://github.com/2captcha)。

3.2.2. Cloudflare挑战页面

使用puppeteer JS进行旁路

- 首先,发送与**独立turnstile验证码**相同的**POST**请求来触发**2Captcha**旁路作业。但是,还有**3**个必填字段需要设置,包括**数据、页面数据和操作**。

```
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*调用。

```
// 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**的文件中,要绕过的脚本则为:

```
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();。

```
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)的日志;

```
// 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*验证。

```
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。祝贺!

![](https://i0.wp.com/blog.nashtechglobal.com/wp-content/uploads/2024/01/Bypass-successfully-cloudflare-1.png?resize=1024%2C532&ssl=1)

4. 总结

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

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

5. 引用

[2Captcha指南:https://2captcha.com/blog/bypass-cloudflare-turnstile-captcha](https://2captcha.com/blog/bypass-cloudflare-turnstile-captcha)

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
爬虫绕过Cloudflare方法可以包括以下几个步骤: 1. 使用代理:Cloudflare可能会根据IP地址来判断请求的真实性。通过使用代理服务器,您可以隐藏您的真实IP地址,使Cloudflare难以识别您的请求是来自机器人还是真实用户。您可以选择使用公开的代理服务器,或者购买专业的代理服务来确保稳定和安全。 2. 改变请求头信息:Cloudflare也会检查请求的头信息来判断是否是机器人。通过修改请求头中的参数,比如User-Agent、Referer等,使其看起来更像是真实用户的请求。您可以随机生成这些参数,以增加其真实性。 3. 模拟人类行为:Cloudflare可以根据爬虫的行为模式来判断是否是机器人。为了避免被阻止,可以模拟人类的浏览行为,比如增加随机的点击、滚动和鼠标移动。这样可以使爬虫的行为更接近真实用户,减少被识别为机器人的概率。 4. 处理验证码:有些网站通过在Cloudflare的反机器人页面上显示验证码来验证用户的身份。爬虫需要能够识别并自动处理这些验证码,以继续访问受保护的页面。可以使用OCR技术或者借助第三方服务来自动识别和解决验证码。 需要注意的是,绕过Cloudflare的反机器人页面可能涉及到违反网站的服务条款和法律法规。在尝试绕过Cloudflare之前,建议您先与网站所有者或管理员进行沟通,以确保您的行为合法且符合网站的规定。同时,谨慎使用这些方法,并遵守相关法律法规,以免引起法律问题。 总结起来,爬虫绕过Cloudflare方法包括使用代理、改变请求头信息、模拟人类行为和处理验证码等。这些方法都旨在模仿真实用户的行为,从而减少被Cloudflare识别为机器人的概率[2]。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值