import psutil import subprocess import time import traceback from selenium import…
- User
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" # ajuste se necessário 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) 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
- User
na verdade o codigo deve validar se o click no i agree foi efetuado para iniciar os outros metodos, pois na tela nao sai da parte de i agree, nao esta clicando
- Assistant
- User
implemente no codigo]
- Assistant
- User
traga o codigo completo com a implementacao
- Assistant