使用Puppeteer爬取bestsecret.at时如何绕过Cloudflare防护?
绕过Cloudflare防护的Puppeteer优化方案
针对你用Puppeteer爬取bestsecret.at时遇到的Cloudflare验证拦截问题,可以尝试以下几种优化手段:
1. 强化Stealth插件的反检测能力
默认的Stealth插件可能不足以应对Cloudflare的高级检测,你可以手动调整规避规则,同时改用主流浏览器的真实User-Agent,避免随机生成的小众UA被标记:
const puppeteer = require('puppeteer-extra'); const StealthPlugin = require('puppeteer-extra-plugin-stealth'); const stealth = StealthPlugin(); // 启用更多反检测规则,移除可能暴露自动化的特征 stealth.enabledEvasions.delete('chrome.runtime'); stealth.enabledEvasions.delete('iframe.contentWindow'); puppeteer.use(stealth); // 使用Chrome主流版本的真实UA const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36';
2. 模拟真实用户操作行为
Cloudflare会通过操作节奏、交互特征识别爬虫,你需要加入随机延迟、滚动、鼠标移动等行为,让流程更贴近真实用户:
(async () => { // 增加更接近真实浏览器的启动参数 const argarr = [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-blink-features=AutomationControlled', '--start-maximized', '--disable-web-security', '--user-data-dir=/tmp/puppeteer-profile' // 用临时用户目录模拟首次打开浏览器 ]; const browser = await puppeteer.launch({ args: argarr, headless: false, // 先以有头模式测试,稳定后再改无头 defaultViewport: null // 使用浏览器默认视口 }); const page = await browser.newPage(); await page.setUserAgent(userAgent); // 页面加载前添加随机延迟 await page.waitForTimeout(Math.random() * 1000 + 500); await page.goto('https://www.bestsecret.at', { waitUntil: 'networkidle2', timeout: 60000 // 延长超时时间,给Cloudflare验证留足时间 }); // 模拟随机滚动 await page.evaluate(() => { window.scrollTo(0, Math.random() * document.body.scrollHeight); }); await page.waitForTimeout(Math.random() * 1500 + 800); // 输入账号密码时添加随机按键延迟 await page.type('#login-username', 'USARENAME', {delay: Math.random() * 100 + 50}); await page.type('#j_password', 'PASSWORD', {delay: Math.random() * 100 + 50}); await page.waitForTimeout(Math.random() * 1000 + 500); await Promise.all([ page.click('#login-button'), page.waitForNavigation({waitUntil: 'networkidle2', timeout: 60000}), ]); // 检测并等待Cloudflare验证完成 const isCloudflarePage = await page.$eval('body', (body) => { return body.innerText.includes('Checking your browser before accessing') || body.classList.contains('cf-browser-verification'); }); if (isCloudflarePage) { console.log('检测到Cloudflare验证,等待完成...'); await page.waitForNavigation({waitUntil: 'networkidle2', timeout: 120000}); } let bodyHTML = await page.content(); console.log(bodyHTML); await browser.close(); })();
3. 降低爬取频率
短时间内频繁请求是触发Cloudflare验证的重要原因,切换页面时增加3-5秒的随机延迟,同时限制并发请求数量,模拟人类的浏览节奏。
4. 处理人机验证(谨慎使用)
如果遇到需要手动点击的验证,可以尝试puppeteer-extra-plugin-recaptcha这类工具自动处理,但注意这类操作可能违反网站的使用条款,使用前需确认网站规则。
内容的提问来源于stack exchange,提问作者mohsen
相关产品推荐
相关产品推荐

