Selenium点击Continuar按钮报错,完成HCaptcha仍无法跳转
问题描述
我尝试访问巴西税务网站(https://www.nfe.fazenda.gov.br/portal/consultaRecaptcha.aspx?tipoConsulta=resumo&tipoConteudo=7PhJ+gAVw2g%3d),需输入NF-e访问密钥、完成HCaptcha验证后点击"Continuar"按钮进入第二个页面。作为Selenium新手,我编写了如下代码:
#import requests from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import time import getpass import keyboard siteGOV = "https://www.nfe.fazenda.gov.br/portal/consultaRecaptcha.aspx?tipoConsulta=resumo&tipoConteudo=7PhJ+gAVw2g%3d"#http://www.nfe.fazenda.gov.br/portal/consultaRecaptcha.aspx?tipoConsulta=resumo&tipoConteudo=7PhJ+gAVw2g=" options = webdriver.ChromeOptions() options.add_extension("Buster-Captcha-Solver-for-Humans.crx") options.add_argument("start-maximized") browser_driver = webdriver.ChromeService() pageToScrap = webdriver.Chrome(options=options) #da o driver usado para pesquisa na net pageToScrap.get(siteGOV) #site acessado acessKey = "" possiveisAlvos = pageToScrap.find_elements(By.TAG_NAME, "input") time.sleep(5) for _i in possiveisAlvos: if _i.accessible_name == "Chave de Acesso da NF-e": _i.send_keys(acessKey) print("got it") _l= True while True: if _l: print("enter input when finishid the captcha") _l = False if keyboard.is_pressed("enter"): break for element in possiveisAlvos: if element.get_attribute("value") == "Continuar": #ACHEI O BOTAO DE CONTINUAR print(element) element.click() break time.sleep(15) pageToScrap.quit()
每次代码点击"Continuar"按钮后,页面加载报错(已附相关截图)。我已手动完成HCaptcha验证,仍出现此问题。经排查,该按钮的onclick事件会调用特定函数,但不知如何解决,请求技术帮助。
解决方案建议
- 避免复用过期元素引用:你提前获取的
possiveisAlvos元素列表,在等待验证码的过程中可能因页面渲染刷新导致引用失效。点击按钮前需重新定位元素,而非使用之前的列表。 - 用显式等待替代固定休眠:
time.sleep稳定性差,改用Selenium显式等待确保元素可交互后再操作:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 点击前重新定位按钮 continuar_btn = WebDriverWait(pageToScrap, 10).until( EC.element_to_be_clickable((By.XPATH, "//input[@value='Continuar']")) ) continuar_btn.click() - 确认HCaptcha验证状态:手动完成验证后,等待页面出现验证成功的标记(如HCaptcha勾选框状态变化),再执行点击操作,确保验证状态已被页面正确识别。
- 模拟真实用户交互:添加少量用户行为模拟,比如输入密钥后点击页面空白区域,或验证完成后等待2-3秒再点击按钮,降低网站自动化检测概率。
- 直接执行onclick函数:通过浏览器开发者工具查看按钮的onclick属性对应的函数(例如
validarFormulario()),尝试直接执行该函数替代元素点击:pageToScrap.execute_script("validarFormulario();")
内容的提问来源于stack exchange,提问作者krasp
相关产品推荐
相关产品推荐

