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

运行绕过reCAPTCHA的Selenium代码时遇JavaScript空值异常求助

解决reCAPTCHA绕过中document.getElementById('g-recaptcha-response')返回null的问题

问题背景

使用Selenium结合2captcha API绕过目标站https://impedimentos.migracion.gob.ec/simiec-consultaImpedimentos/的reCAPTCHA时,代码在演示站可正常运行,但更换目标站site key后,WebDriverWait等待g-recaptcha-response元素存在的步骤成功,后续执行JavaScript设置innerHTML时抛出Cannot set properties of null错误。

核心原因

目标站的reCAPTCHA响应元素(g-recaptcha-response)嵌套在iframe中,而你的代码直接在主文档上下文执行JavaScript,无法获取到iframe内的元素。演示站可能未使用iframe嵌套,因此代码可以正常运行。

解决方案

需要先切换到reCAPTCHA对应的iframe上下文,再执行元素操作,完成后切回主文档。修改后的代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

from solveRecaptcha import solveRecaptcha

browser = webdriver.Chrome()
browser.get('https://impedimentos.migracion.gob.ec/simiec-consultaImpedimentos/')

result = solveRecaptcha(
    "6Ld38BkUAAAAAPATwit3FXvga1PI6iVTb6zgXw62",
    "https://impedimentos.migracion.gob.ec/simiec-consultaImpedimentos/"
)

code = result['code']
print(code)

# 等待reCAPTCHA iframe加载并切换到该iframe
WebDriverWait(browser, 10).until(
    EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src*='recaptcha']"))
)

# 在iframe上下文内设置g-recaptcha-response的值
browser.execute_script(
    f"document.getElementById('g-recaptcha-response').innerHTML = '{code}';"
)

# 切回主文档上下文
browser.switch_to.default_content()

# 触发验证后的提交操作(替换为目标站的提交按钮选择器)
# browser.find_element(By.ID, "your-submit-button-id").click()

time.sleep(120)  # 修正原代码的空格错误

额外注意事项

  • 不要点击g-recaptcha-response元素:该元素通常是隐藏状态,点击不会触发验证逻辑,应直接提交表单或点击页面的提交按钮。
  • 若iframe选择器不生效:可以尝试用By.CLASS_NAME, "g-recaptcha"定位包含iframe的容器,再获取其内部的iframe元素。
  • 动态元素处理:如果目标站的iframe属性动态变化,可以调整等待条件,确保iframe完全加载后再切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:25:57