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

使用Selenium无法定位reCAPTCHA复选框按钮的问题求助

解决Selenium无法定位reCAPTCHA复选框的问题

你的核心问题是reCAPTCHA元素不在主页面的DOM中,而是嵌套在独立的<iframe>里,Selenium默认只会搜索当前上下文(主页面)的元素,所以直接定位肯定找不到。另外代码里还有一个小问题:soup = BeautifulSoup(driver.page_source, 'html.parser')这行在函数外部,driver是函数内的局部变量,运行时会抛出未定义错误。

修复步骤:

  1. 切换到reCAPTCHA的iframe:先定位包含reCAPTCHA的iframe,切换上下文后再查找目标元素。
  2. 调整变量作用域:把页面源码解析逻辑放到函数内部,确保能访问到driver对象。

修正后的代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup

def captcha(url = "https://google.com/recaptcha/api2/demo"):
    driver = webdriver.Chrome()
    driver.get(url)
    delay = 10  # 适当延长等待时间,确保iframe加载完成

    try:
        # 等待reCAPTCHA的iframe加载并切换进去
        iframe = WebDriverWait(driver, delay).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'iframe[src*="recaptcha/api2/anchor"]'))
        )
        driver.switch_to.frame(iframe)
        
        # 定位可交互的reCAPTCHA复选框
        captcha_checkbox = WebDriverWait(driver, delay).until(
            EC.element_to_be_clickable((By.CLASS_NAME, 'recaptcha-checkbox-border'))
        )
        print("Captcha is present in the DOM \n\n")
        # 这里可以添加点击逻辑:captcha_checkbox.click()
        
        # 解析iframe内的页面源码
        soup = BeautifulSoup(driver.page_source, 'html.parser')
        print(soup)
        
        # 切换回主页面(如果后续需要操作主页面元素)
        driver.switch_to.default_content()
        
    except TimeoutException:
        print("Captcha did not show up\n\n")
    finally:
        driver.quit()  # 确保浏览器关闭,避免残留进程

captcha()

关键说明:

  • iframe切换:reCAPTCHA的核心元素都在独立iframe中,必须先用driver.switch_to.frame()切换上下文才能访问。
  • 等待条件:用element_to_be_clickable替代presence_of_element_located更合理,确保元素不仅存在还能交互。
  • 资源清理:添加finally块保证浏览器进程被正确关闭。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:46:03