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

Selenium+2captcha项目遇g-recaptcha-response字段验证失败问题求助

问题:Selenium填入reCAPTCHA响应后点击登录仍提示“必填字段不能为空”

我开发了一个使用Selenium登录网站、借助2captcha解决reCAPTCHA的程序。在将验证结果填入id为g-recaptcha-response的textarea后,点击登录按钮时网站仍提示“必填字段不能为空”错误,无法继续操作。我认为问题与2captcha无关,更可能出在Selenium上。

错误提示来自网站而非reCAPTCHA。

相关代码如下:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from solveRecaptcha import solveRecaptcha
import json

accounts = json.load(open('accounts.json', 'r', encoding='utf-8'))

options = Options()
options.binary_location = r'C:\Program Files\Firefox Developer Edition\firefox.exe'
driver = webdriver.Firefox(options=options)
driver.get('link')
driver.implicitly_wait(10)
driver.find_element(By.ID, 'email-input').send_keys(accounts['email'])
driver.find_element(By.ID, 'password-input').send_keys(accounts['password'])
result = solveRecaptcha("sitekey", "link")
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'g-recaptcha-response'))
)
driver.execute_script("document.getElementById('g-recaptcha-response').innerHTML = " + "'" + result + "'" ) # 该行无报错,通过开发者工具能看到结果已填入
driver.find_element(By.ID, 'login-btn').click() # 点击按钮后提示“必填字段不能为空”
driver.implicitly_wait(1000)

解决方法

核心问题

直接修改g-recaptcha-response的innerHTML,既没有设置该字段的实际表单值value,也没有触发网站表单校验需要的字段变更事件,导致前端仍判定该字段为空。

具体修复方案

  1. 正确设置字段值并触发变更事件
    替换原有的execute_script代码,改为设置value属性并手动触发input/change事件,同时用参数传递验证码结果避免字符串转义问题:

    # 替换原execute_script行
    driver.execute_script("""
        const responseField = document.getElementById('g-recaptcha-response');
        responseField.value = arguments[0];
        // 触发字段变更事件,告知网站表单该字段已填写
        responseField.dispatchEvent(new Event('input'));
        responseField.dispatchEvent(new Event('change'));
    """, result)
    
  2. 等待reCAPTCHA状态同步完成
    填入响应后不要立即点击登录,等待reCAPTCHA完成内部状态更新:

    # 填入响应后添加等待逻辑,可根据页面实际元素调整
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '.g-recaptcha[data-state="verified"]'))
    )
    

    若无法找到明确的验证状态元素,可临时添加短暂等待:

    import time
    time.sleep(2) # 等待2秒让reCAPTCHA完成状态同步
    
  3. 避免隐式等待与显式等待混用
    代码中同时使用implicitly_wait和WebDriverWait会导致等待逻辑混乱,建议统一使用显式等待,删除所有driver.implicitly_wait()调用。

  4. 检查是否存在额外校验字段
    部分网站会有隐藏的辅助校验字段,可通过浏览器开发者工具查看登录请求的表单数据,对比手动登录与Selenium登录的提交参数差异,确保所有必要字段都已正确填充。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:22:40