ajuste o meu codigo somente para clicar no botao <button class="lg secondary…
- User
ajuste o meu codigo somente para clicar no botao I Agree quando aparece na tela, e remova todo o resto:
import psutil import subprocess import time import traceback from selenium import webdriver from selenium.webdriver.chrome.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 bs4 import BeautifulSoup
def chrome_debug_esta_rodando(): print("Verificando se o Chrome no modo debug já está rodando...") for proc in psutil.process_iter(['cmdline']): try: cmdline = proc.info['cmdline'] if cmdline and any('chrome.exe' in part.lower() for part in cmdline): if any('--remote-debugging-port=9222' in part for part in cmdline): print("Chrome debug detectado em execução.") return True except (psutil.NoSuchProcess, psutil.AccessDenied): continue print("Chrome debug não encontrado.") return False
def abrir_chrome_com_debug(): caminho_chrome = r"C:\Program Files\Google\Chrome\Application\chrome.exe" args = [ caminho_chrome, '--remote-debugging-port=9222', '--user-data-dir=C:\temp\chrome-debug' ] print("Abrindo Chrome com modo debug e perfil específico...") subprocess.Popen(args) # Aguarda o Chrome abrir esperando pela janela do Chrome com modo debug timeout = 30 interval = 1 tempo_inicial = time.time() while True: if chrome_debug_esta_rodando(): print("Chrome aberto com debug e pronto.") break if time.time() - tempo_inicial > timeout: print("Timeout ao tentar abrir Chrome com debug.") break time.sleep(interval)
def pegar_ultima_mensagem_bot(driver): try: print("Tentando pegar última mensagem do bot...") bubble_wrap = driver.find_element(By.CSS_SELECTOR, 'div.bubble-wrap[role="log"][aria-label*="chatbot conversation"]') html_conversa = bubble_wrap.get_attribute('innerHTML')
soup = BeautifulSoup(html_conversa, 'html.parser') bot_messages = soup.find_all('div', {'data-testid': 'bot'}) mensagens_validas = [] for msg_div in bot_messages: p = msg_div.find('p') if p: texto = p.get_text(strip=True) if texto and "ModuleNotFoundError" not in texto: mensagens_validas.append(texto) if mensagens_validas: print("Última mensagem válida encontrada:", mensagens_validas[-1]) return mensagens_validas[-1] # Retorna a última mensagem válida else: print("Nenhuma mensagem válida encontrada.") except Exception as ex: print("Erro ao extrair mensagem do bot:", ex) traceback.print_exc() return Nonedef esperar_mensagem_bot(driver, timeout=30, poll_interval=1): print(f"Iniciando espera por nova mensagem do bot (timeout={timeout}s)...") tempo_inicial = time.time() ultima_msg_anterior = pegar_ultima_mensagem_bot(driver)
while True: try: ultima_msg_atual = pegar_ultima_mensagem_bot(driver) if ultima_msg_atual and ultima_msg_atual != ultima_msg_anterior: print("Nova mensagem do bot detectada!") return ultima_msg_atual if (time.time() - tempo_inicial) > timeout: print("Timeout atingido na espera pela mensagem do bot.") return None time.sleep(poll_interval) except Exception as e: print("Erro durante espera pela mensagem do bot:", e) traceback.print_exc() return None - Assistant
Claro! Segue o seu código ajustado apenas para clicar no botão
<button class="lg secondary svelte-1ixn6qd" id="component-23"> I Agree</button>quando ele aparecer na tela, removendo todo o resto.import time import traceback from selenium import webdriver from selenium.webdriver.chrome.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 def clicar_botao_i_agree(): try: chrome_options = Options() chrome_options.debugger_address = "127.0.0.1:9222" driver = webdriver.Chrome(options=chrome_options) wait = WebDriverWait(driver, 30) print("Esperando botão 'I Agree' aparecer na página...") # Espera até o botão estar clicável botao = wait.until(EC.element_to_be_clickable( (By.CSS_SELECTOR, 'button#component-23.lg.secondary.svelte-1ixn6qd'))) print("Botão 'I Agree' encontrado. Clicando...") botao.click() print("Botão clicado com sucesso.") # Pode deixar o driver aberto ou fechar conforme necessário: driver.quit() return True except Exception as e: print("Erro ao tentar clicar no botão 'I Agree':", e) traceback.print_exc() try: driver.quit() except: pass return False if __name__ == "__main__": clicar_botao_i_agree()