meu cosigo esta dando certo, porem percebi que ele comeca a dar erro depois de algumas tentativaas, mude o codigo para printar em qual momento ele da erro e pegar o log do erro: import psutil
import subprocess
import time
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():
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):
return True
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
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'
]
subprocess.Popen(args)
time.sleep(5)
def pegar_ultima_mensagem_bot(driver):
try:
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:
return mensagens_validas[-1] # Retorna a última mensagem válida
except Exception as ex:
print("Erro ao extrair mensagem do bot:", ex)
return None
def esperar_mensagem_bot(driver, timeout=30, poll_interval=1):
tempo_inicial = time.time()
ultima_msg_anterior = pegar_ultima_mensagem_bot(driver)
while True:
ultima_msg_atual = pegar_ultima_mensagem_bot(driver)
if ultima_msg_atual and ultima_msg_atual != ultima_msg_anterior:
return ultima_msg_atual
if (time.time() - tempo_inicial) > timeout:
return None
time.sleep(poll_interval)
def abrir_aba_no_chrome(url):
chrome_options = Options()
chrome_options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=chrome_options)
driver.execute_script(f"window.open('{url}', '_blank');")
driver.switch_to.window(driver.window_handles[-1])
print(f"Aba aberta no Chrome: {url}")
time.sleep(5) # espera carregar a página
iframes = driver.find_elements(By.TAG_NAME, 'iframe')
print(f"iframes encontrados: {len(iframes)}")
wait = WebDriverWait(driver, 60)
iframe_index_para_usar = None
# Tenta encontrar iframe que contenha o textarea para enviar mensagem
for idx, iframe in enumerate(iframes):
try:
driver.switch_to.default_content()
driver.switch_to.frame(iframe)
print(f"Tentando iframe {idx}")
textarea = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'textarea[placeholder="Hi there!"]')))
print(f"Textarea encontrado no iframe {idx}")
iframe_index_para_usar = idx
break
except Exception as e:
print(f"Textarea não encontrado no iframe {idx}, tentando próximo iframe.")
if iframe_index_para_usar is None:
print("Textarea não encontrado em nenhum iframe, finalizando.")
driver.quit()
return
driver.switch_to.default_content()
driver.switch_to.frame(iframes[iframe_index_para_usar])
# Digita "oi"
textarea = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'textarea[placeholder="Hi there!"]')))
textarea.clear()
textarea.send_keys("oi")
print("Texto 'oi' digitado no input.")
time.sleep(1) # pequena pausa antes do clique
run_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[normalize-space()="Run"]')))
run_button.click()
print("Botão 'Run' clicado.")
# Aguarda a resposta nova do bot dinamicamente
print("Aguardando resposta do bot...")
ultima_msg = esperar_mensagem_bot(driver, timeout=30, poll_interval=1)
if ultima_msg:
print("Última mensagem do bot:", ultima_msg)
else:
print("Timeout: não foi possível capturar a última mensagem do bot.")
driver.quit()
def main():
if not chrome_debug_esta_rodando():
print("Chrome no modo debug não está rodando. Abrindo Chrome com modo debug.")
abrir_chrome_com_debug()
else:
print("Chrome no modo debug já está rodando.")
abrir_aba_no_chrome("https://huggingface.co/spaces/yuntian-deng/ChatGPT")
if name == "main":
main()