You need to enable JavaScript to run this app. 如何在Python Selenium Chromedriver项目中接入Capmonster解决ReCaptcha
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Selenium Chromedriver项目中接入Capmonster解决ReCaptcha

ReCaptcha自动求解适配实现逻辑

适配完全基于现有Selenium脚本结构扩展,不需要重构原有线程、驱动初始化逻辑,核心链路为:页面参数提取 → 调用Capmonster求解接口 → 结果注入触发页面验证。

分步代码改造

1. 补充依赖安装

首先安装HTTP请求依赖,用于调用Capmonster接口,安装完成后在现有代码的导入区域新增import requests:

pip install requests

2. 封装Capmonster交互逻辑

新增两个独立函数,分别负责提交求解任务、轮询获取求解结果,注意将CAPMONSTER_API_KEY替换为你自己持有的密钥:

CAPMONSTER_API_KEY = "你的Capmonster密钥"

def create_recaptcha_task(website_url, website_key):
    payload = {
        "clientKey": CAPMONSTER_API_KEY,
        "task": {
            "type": "NoCaptchaTaskProxyless",
            "websiteURL": website_url,
            "websiteKey": website_key
        }
    }
    # 调用Capmonster创建任务接口
    resp = requests.post("<Capmonster任务创建接口地址>", json=payload).json()
    if resp.get("errorId") != 0:
        raise Exception(f"创建任务失败: {resp.get('errorDescription')}")
    return resp["taskId"]

def get_task_result(task_id):
    payload = {
        "clientKey": CAPMONSTER_API_KEY,
        "taskId": task_id
    }
    # 循环轮询直到任务完成
    while True:
        # 调用Capmonster结果查询接口
        resp = requests.post("<Capmonster结果查询接口地址>", json=payload).json()
        if resp.get("errorId") != 0:
            raise Exception(f"查询结果失败: {resp.get('errorDescription')}")
        if resp["status"] == "ready":
            return resp["solution"]["gRecaptchaResponse"]
        time.sleep(2)

3. 新增页面ReCaptcha参数提取逻辑

从打开的目标页面中自动提取ReCaptcha求解必需的站点密钥(site key),支持从DOM元素、iframe源码两种位置提取,兼容绝大多数页面的ReCaptcha部署方式,用到的NoSuchElementException你现有代码已经导入,不需要额外引入:

def get_recaptcha_sitekey(driver):
    # 优先从带g-recaptcha类名的DOM元素提取data-sitekey属性
    try:
        recaptcha_el = driver.find_element(By.CLASS_NAME, "g-recaptcha")
        return recaptcha_el.get_attribute("data-sitekey")
    except NoSuchElementException:
        # 元素不存在时遍历所有iframe,从recaptcha域名的src参数中解析sitekey
        iframes = driver.find_elements(By.TAG_NAME, "iframe")
        for iframe in iframes:
            src = iframe.get_attribute("src")
            if "recaptcha" in src:
                return src.split("k=")[1].split("&")[0]
    raise NoSuchElementException("未定位到页面中的ReCaptcha站点密钥")

4. 新增验证码Token注入逻辑

拿到Capmonster返回的验证码token后,直接注入到页面隐藏的ReCaptcha响应输入框,并触发页面内置的验证回调,避免页面检测到token被篡改:

def inject_recaptcha_token(driver, token):
    # 给隐藏的g-recaptcha-response输入框赋值
    driver.execute_script(f"""
        document.querySelector('#g-recaptcha-response').innerHTML = '{token}';
        document.querySelector('#g-recaptcha-response').style.display = 'block';
    """)
    # 触发ReCaptcha客户端的内置回调,让页面识别验证状态
    driver.execute_script(f"""
        if (typeof window.___grecaptcha_cfg !== 'undefined') {{
            Object.values(window.___grecaptcha_cfg.clients).forEach(client => {{
                Object.values(client).forEach(key => {{
                    if (key.callback) key.callback('{token}');
                }})
            }})
        }}
    """)

5. 整合原有测试函数

将上述逻辑嵌入你现有的test函数中,保留原有的截图、线程启动逻辑,同时补充异常捕获:

def test(driver, url):
    driver.get(url)
    try:
        # 等待ReCaptcha元素加载完成,最多等15秒
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CLASS_NAME, "g-recaptcha"))
        )
        # 提取站点密钥
        site_key = get_recaptcha_sitekey(driver)
        # 创建求解任务、等待结果
        task_id = create_recaptcha_task(url, site_key)
        recaptcha_token = get_task_result(task_id)
        # 注入token完成验证
        inject_recaptcha_token(driver, recaptcha_token)
        print("ReCaptcha自动求解完成")
    except TimeoutException:
        # 超过等待时间没找到验证码,说明页面未触发验证,直接走原有逻辑
        print("页面未检测到ReCaptcha验证,跳过求解流程")
    try:
        driver.save_screenshot('C:\\Users\\yvesb\\Downloads\\headless_chrome_test7.png')
    finally:
        print("screenshot done")
关键注意事项
  • 原代码中Selenium驱动初始化的chrome_options参数在Selenium 4+版本已弃用,建议替换为options=options传入,避免版本兼容报错
  • 如果求解的token始终无法通过验证,检查是否存在IP不匹配问题:如果Capmonster任务未使用和Selenium访问页面相同的代理,返回的token会被站点判定为无效,需要在创建任务时补充对应代理参数
  • Headless模式下的Selenium容易被站点反爬机制识别,建议在浏览器初始化参数中补充options.add_experimental_option("excludeSwitches", ["enable-automation"])、options.add_argument("--disable-blink-features=AutomationControlled"),降低触发验证的概率
  • 提取site key时必须等DOM完全渲染完成,不要在页面刚发起请求时就取值,否则可能拿到空值导致求解失败

内容的提问来源于stack exchange,提问作者Yves1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 15:54:05