如何用Python的Selenium ChromeDriver绕过Cloudflare人机验证
解决Selenium ChromeDriver无法绕过Cloudflare人机验证的问题
问题说明
使用Selenium ChromeDriver访问目标网站时,遇到Cloudflare的“verify that you are human”复选框验证:
- 即使手动点击复选框也无法通过,但在普通Chrome浏览器中可正常完成验证
- 已尝试常规反检测参数,均无效果:
--disable-blink-features=AutomationControlledoptions.add_experimental_option("excludeSwitches", ["enable-automation"])options.add_experimental_option('useAutomationExtension', False)
已尝试的无效方案
- 使用SeleniumBase的UC模式,但搭配MetaMask扩展后UC模式失效
- 尝试SeleniumWire隐身模式、undetected-chromedriver均无效
- 用十六进制编辑器修改ChromeDriver移除
cdc标识,导致Selenium报win32 API错误
可行解决思路
1. 隔离MetaMask扩展与UC模式
SeleniumBase的UC模式会对Chrome做反检测修改,直接加载扩展可能破坏配置,可换两种方式加载MetaMask:
- 先启动UC模式浏览器,模拟手动安装MetaMask扩展(通过浏览器扩展安装流程)
- 加载已配置好MetaMask的Chrome用户数据目录:
with SB(uc=True, incognito=False, user_data_dir="path/to/your/chrome-profile", proxy=proxy, agent=agent) as sb: sb.driver.uc_open_with_reconnect(url, 3) # 后续验证操作
2. 安全修改ChromeDriver的cdc标识
直接用十六进制编辑器修改易破坏文件结构,建议用脚本自动替换:
import os import re def patch_chromedriver(path): with open(path, 'rb') as f: data = f.read() # 将cdc_开头的特征字符串替换为随机字符 data = re.sub(b'cdc_[a-zA-Z0-9]+', b'xxx_abcdefghijklmn', data) with open(path, 'wb') as f: f.write(data) # 调用示例 patch_chromedriver("path/to/chromedriver.exe")
注意:每次ChromeDriver更新后需重新执行该脚本。
3. 调整验证操作的时机与逻辑
Cloudflare验证iframe加载存在延迟,需优化操作顺序:
with SB(uc=True, proxy=proxy, agent=agent) as sb: sb.driver.uc_open_with_reconnect(url, 3) # 等待验证iframe加载完成 sb.wait_for_element_present('iframe[title="Widget containing a Cloudflare security challenge"]', timeout=10) sb.driver.switch_to.frame(sb.find_element('iframe[title="Widget containing a Cloudflare security challenge"]')) # 等待复选框可点击 sb.wait_for_element_clickable('#challenge-stage input[type="checkbox"]', timeout=10) sb.uc_click('#challenge-stage input[type="checkbox"]', reconnect_time=4) # 切回主文档 sb.driver.switch_to.default_content() # 等待验证通过后页面加载 sb.wait_for_page_load(timeout=15)
4. 确保Chrome与ChromeDriver版本匹配
必须保证Chrome浏览器和ChromeDriver的版本完全一致,版本不匹配会导致反检测机制失效或兼容性错误。
5. 验证代理配置有效性
确认user:password@ip:port格式的代理在SeleniumBase中正确生效,可访问https://httpbin.org/ip检查代理IP是否正常显示。
内容的提问来源于stack exchange,提问作者Freyr
相关产品推荐
相关产品推荐

