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

Selenium自动表单提交遇reCAPTCHA无限重置问题求助

表单自动提交reCAPTCHA问题排查请求

我正在开发一个自动表单提交项目,使用Selenium可完成表单填充,但点击提交按钮后会触发reCAPTCHA验证。尝试通过2captcha绕过验证未成功,手动完成验证后验证状态又会重置,请求协助排查代码问题。

我的代码

import time
import os
import requests
import random
import string
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver as wd
import sys

def random_char(y):
    return ''.join(random.choice(string.ascii_letters) for x in range(y))
mail = (random_char(7)+"@gmail.com")

driver = wd.Firefox(executable_path='C:\geckodriver.exe')
target_url = 'https://www.yemeksepeti.com/login/new?step=registration'
driver.get(target_url)
driver.maximize_window()
time.sleep(2)
print(mail)
time.sleep(2)
email = str(mail)
time.sleep(2)
firstName = 'Mert'
time.sleep(2)
lastName = 'Demir'
time.sleep(2)
birthDate = '01-04-2001'
time.sleep(2)
password = 'AbcAbc123.*_123'
time.sleep(2)
emailPath = driver.find_element("xpath", '//*[@id="email"]')
time.sleep(2)
emailPath.send_keys(mail)
time.sleep(2)
firstNamePath = driver.find_element("xpath", '//*[@id="first_name"]')
time.sleep(2)
firstNamePath.send_keys(firstName)
time.sleep(2)
lastNamePath = driver.find_element("xpath", '//*[@id="last_name"]')
time.sleep(2)
lastNamePath.send_keys(lastName)
time.sleep(2)
birthDatePath = driver.find_element("xpath", '//*[@id="birthdate"]')
time.sleep(2)
birthDatePath.send_keys(birthDate)
time.sleep(2)
passwordPath = driver.find_element("xpath", '//*[@id="password"]')
time.sleep(2)
passwordPath.send_keys(password)
time.sleep(2)
Submit = driver.find_element("xpath", '//*[@id="login-page-react-root"]/main/div/form/div[8]/button')
Submit.click()
time.sleep(2)

问题排查与解决建议

1. 替换硬编码等待为显式等待

代码中大量使用time.sleep(2),固定等待会导致操作节奏完全不符合真人行为,还可能因元素未加载完全引发异常,这也是触发反爬、导致验证状态重置的核心原因之一。建议改用Selenium的显式等待:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 示例:等待邮箱输入框可点击后再操作
emailPath = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "email"))
)
emailPath.send_keys(mail)

2. 隐藏浏览器自动化指纹

默认Firefox驱动会暴露webdriver标识,容易被网站检测为自动化工具,直接导致验证会话失效。可以通过以下方式伪装浏览器指纹:

from selenium.webdriver.firefox.options import Options

options = Options()
# 可选:启用无头模式(若不需要可视化操作)
options.add_argument("--headless")
# 隐藏自动化控制特征
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = wd.Firefox(executable_path='C:\geckodriver.exe', options=options)
# 执行脚本移除navigator.webdriver标识
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

3. 正确集成2captcha流程

当前代码没有2captcha的集成逻辑,之前的尝试大概率存在流程错误。正确的集成步骤如下:

  1. 提取页面中reCAPTCHA的data-sitekey属性值
  2. 调用2captcha API提交验证请求
  3. 等待API返回验证结果
  4. 将验证token注入页面后再提交表单

示例代码(替换为你的2captcha API密钥):

# 获取reCAPTCHA的sitekey
sitekey = driver.find_element(By.CSS_SELECTOR, 'div.g-recaptcha').get_attribute('data-sitekey')

# 调用2captcha API提交验证任务
api_key = "你的2captcha密钥"
submit_url = f"http://2captcha.com/in.php?key={api_key}&method=userrecaptcha&googlekey={sitekey}&pageurl={target_url}"
response = requests.get(submit_url)

if response.text.startswith('OK'):
    captcha_id = response.text.split('|')[1]
    # 等待验证码解决
    time.sleep(15)
    # 获取验证结果
    result_url = f"http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}"
    result_response = requests.get(result_url)
    
    while result_response.text == 'CAPCHA_NOT_READY':
        time.sleep(5)
        result_response = requests.get(result_url)
    
    if result_response.text.startswith('OK'):
        captcha_token = result_response.text.split('|')[1]
        # 将token注入页面的reCAPTCHA响应框
        driver.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML='{captcha_token}';")
        driver.execute_script("grecaptcha.execute();")
        # 等待验证完成后再提交表单
        Submit.click()

4. 验证状态重置的核心原因

手动完成验证后状态重置,本质是网站检测到了自动化行为(比如异常操作节奏、浏览器指纹),导致验证会话被强制失效。优先解决前面的等待方式和指纹伪装问题,再重新测试验证流程。

内容的提问来源于stack exchange,提问作者Hakan Yazıcı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:30:52