You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用2Captcha解决带回调的reCAPTCHA v2遇阻:验证按钮无法定位

问题:无头模式下reCAPTCHA v2验证窗口无法关闭

我正在解决带回调的reCAPTCHA v2图片验证问题,仅在无头模式下会触发该验证码。目前已成功提取回调并配合2Captcha完成求解,提交后页面可跳转至下一页,但验证码窗口仍处于打开状态。我尝试多种方法切换iframe,却始终无法通过XPath、CSS选择器等找到并点击“verify”按钮,希望有人能帮忙排查问题所在。

相关代码

def solve_recaptcha(api_key, site_key, url):
    print(f"Sending sitekey to 2Captcha: {site_key}")
    # Send the sitekey to 2Captcha for solving
    response = requests.post(
        'http://2captcha.com/in.php',
        data={
            'key': api_key,
            'method': 'userrecaptcha',
            'googlekey': site_key,
            'pageurl': url
        }
    )
    print(f"2Captcha response: {response.text}")
    if response.text.startswith('OK|'):
        captcha_id = response.text.split('|')[1]
    else:
        raise Exception(f"Error from 2Captcha: {response.text}")

    # Retrieve the CAPTCHA solution
    while True:
        time.sleep(5)
        result = requests.get(f'http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}')
        if result.text == 'CAPCHA_NOT_READY':
            continue
        if result.text.startswith('OK|'):
            captcha_solution = result.text.split('|')[1]
            break
        else:
            raise Exception(f"Error from 2Captcha: {result.text}")

    print(f"CAPTCHA Solution: {captcha_solution}")
    return captcha_solution

try:
    # JavaScript function to find reCAPTCHA clients
    find_recaptcha_clients_js = """
    function findRecaptchaClients() {
      if (typeof (___grecaptcha_cfg) !== 'undefined') {
        return Object.entries(___grecaptcha_cfg.clients).map(([cid, client]) => {
          const data = { id: cid, version: cid >= 10000 ? 'V3' : 'V2' };
          const objects = Object.entries(client).filter(([_, value]) => value && typeof value === 'object');

          objects.forEach(([toplevelKey, toplevel]) => {
            const found = Object.entries(toplevel).find(([_, value]) => (
              value && typeof value === 'object' && 'sitekey' in value && 'size' in value
            ));

            if (typeof toplevel === 'object' && toplevel instanceof HTMLElement && toplevel['tagName'] === 'DIV'){
                data.pageurl = toplevel.baseURI;
            }

            if (found) {
              const [sublevelKey, sublevel] = found;

              data.sitekey = sublevel.sitekey;
              const callbackKey = data.version === 'V2' ? 'callback' : 'promise-callback';
              const callback = sublevel[callbackKey];
              if (!callback) {
                data.callback = null;
                data.function = null;
              } else {
                data.function = callback;
                const keys = [cid, toplevelKey, sublevelKey, callbackKey].map((key) => `['${key}']`).join('');
                data.callback = `___grecaptcha_cfg.clients${keys}`;
              }
            }
          });
          return data;
        });
      }
      return [];
    }
    return findRecaptchaClients();
    """

    # Execute the JavaScript function to get reCAPTCHA clients data
    recaptcha_data = driver.execute_script(find_recaptcha_clients_js)
    print(f"reCAPTCHA Data: {recaptcha_data}")

    if recaptcha_data:
        # Assuming the first reCAPTCHA client found is the target
        recaptcha_info = recaptcha_data[0]
        site_key = recaptcha_info['sitekey']
        callback_function = recaptcha_info.get('callback')

        # Solve the reCAPTCHA
        captcha_solution = solve_recaptcha(api_key, site_key, url)

        # Inject the solved token into the page
        driver.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML='{captcha_solution}';")

        # Execute the callback function if it exists
        if callback_function:
            driver.execute_script(f"var callback = {callback_function}; callback('{captcha_solution}');")
        
        print("CAPTCHA solved and token submitted successfully.")
    else:
        print("No reCAPTCHA found on the page.")

except Exception as e:
    print(f"Error: {e}")

尝试过的iframe定位代码(失败)

driver.switch_to.frame(0)
wait = WebDriverWait(driver, 10)
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[id*='verify']")))

# Click the button
button.click()
print("Button clicked successfully!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:45:55