remova do codigo a abertura de uma nova pagina, esta abrindo e nao esta executando o…
Jump to turn (6)
- User
remova do codigo a abertura de uma nova pagina, esta abrindo e nao esta executando o codigo de fazer o input : 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 None
def 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
def abrir_aba_no_chrome(url): try: print("Inicializando webdriver com debug em 127.0.0.1:9222") chrome_options = Options() chrome_options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=chrome_options)
print(f"Abrindo nova aba com URL: {url}")
driver.execute_script(f"window.open('{url}', '_blank');")
driver.switch_to.window(driver.window_handles[-1])
print("Alternando para a aba aberta.")
wait = WebDriverWait(driver, 30)
# Aguarda até que pelo menos 1 iframe esteja presente na página
wait.until(lambda d: len(d.find_elements(By.TAG_NAME, 'iframe')) > 0)
print("Iframe(s) carregado(s).")
iframes = driver.find_elements(By.TAG_NAME, 'iframe')
print(f"Quantidade de iframes encontrados na página: {len(iframes)}")
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 encontrar textarea no 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. Erro: {e}")
if iframe_index_para_usar is None:
print("Textarea não encontrado em nenhum iframe, finalizando execução.")
driver.quit()
return False # sinaliza falha
# Volta para o iframe que possui o textarea
driver.switch_to.default_content()
driver.switch_to.frame(iframes[iframe_index_para_usar])
print("Preparando para digitar no textarea...")
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.")
# Pequena pausa para garantir o texto inserido - muito menor que antes
time.sleep(0.5)
run_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[normalize-space()="Run"]')))
run_button.click()
print("Botão 'Run' clicado, aguardando resposta do bot...")
ultima_msg = esperar_mensagem_bot(driver, timeout=30, poll_interval=1)
if ultima_msg:
print("Última mensagem do bot capturada com sucesso:", ultima_msg)
resultado = True
else:
print("Timeout: não foi possível capturar a última mensagem do bot.")
resultado = False
driver.quit()
return resultado
except Exception as err:
print(f"\nErro inesperado em abrir_aba_no_chrome: {err}")
traceback.print_exc()
try:
driver.quit()
except Exception:
pass
return False
def main(): try: 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.")
tentativas = 10
for i in range(1, tentativas + 1):
print(f"\n=== Tentativa {i} de {tentativas} ===")
sucesso = abrir_aba_no_chrome("https://huggingface.co/spaces/yuntian-deng/ChatGPT")
if sucesso:
print(f"Tentativa {i} finalizada com sucesso.")
else:
print(f"Tentativa {i} terminou com erro.")
time.sleep(3) # pequena pausa entre tentativas
print("Execução das tentativas finalizada.")
except Exception as e:
print("Erro fatal em main:", e)
traceback.print_exc()
if name == "main": main()
Para remover a abertura de uma nova aba pelo Selenium — que no seu código está sendo feita pela linha:
driver.execute_script(f"window.open('{url}', '_blank');")
driver.switch_to.window(driver.window_handles[-1])
— você deve substituir essa lógica para carregar diretamente a URL na aba já existente que está conectada via debugger.
Ou seja, em vez de abrir uma nova aba e mudar para ela, use o driver para navegar para a URL na aba atual, assim:
driver.get(url)
Encontre a função abrir_aba_no_chrome e dentro dela substitua o trecho:
print(f"Abrindo nova aba com URL: {url}")
driver.execute_script(f"window.open('{url}', '_blank');")
driver.switch_to.window(driver.window_handles[-1])
print("Alternando para a aba aberta.")
por:
print(f"Navegando para a URL na aba existente: {url}")
driver.get(url)
Com isso, você não abrirá uma nova aba, usará a aba já aberta no Chrome em modo debug e evitará problemas com scripts que não interagem bem com múltiplas abas.
abrir_aba_no_chrome (parcial):def abrir_aba_no_chrome(url):
try:
print("Inicializando webdriver com debug em 127.0.0.1:9222")
chrome_options = Options()
chrome_options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=chrome_options)
print(f"Navegando para a URL na aba existente: {url}")
driver.get(url)
wait = WebDriverWait(driver, 30)
# Aguarda até que pelo menos 1 iframe esteja presente na página
wait.until(lambda d: len(d.find_elements(By.TAG_NAME, 'iframe')) > 0)
print("Iframe(s) carregado(s).")
# (restante do seu código permanece igual...)
Se precisar que eu envie o código completo com essa alteração, me avise!
quero o codigo
Claro! Aqui está o seu código completo com a remoção da abertura de nova aba — substituindo a parte que fazia window.open() por um driver.get(url) para carregar a página diretamente na aba existente:
nao funcionou, faca somente com que o codigo verifique se a aba esta abeta na sessao especifica, adicione o input, run, leia a ultima resposta e faca o print no terminal
Entendi. Você quer que o código conecte ao Chrome em modo debug usando o perfil especificado e utilize somente a aba já aberta, sem abrir novas abas ou navegar para URLs diferentes, fazendo o input, clicando no botão 'Run', lendo a última resposta e imprimindo no terminal.
Ou seja:
https://huggingface.co/spaces/yuntian-deng/ChatGPT) está aberta.textarea, clique no botão Run.oi
Oi! Como posso ajudar você?
me ajude a reconhecer o botao i agree e clicar nele, esta dando erro pelo id, tente de diversas formas antes de fazer o input reconheca se a primeira pagina tem o botao i agree: GPT-4.1 mini: Research Preview (Short-Term Availability) This app provides you full access to GPT-4.1 mini (1M token limit). You don't need any OPENAI API key. Chatbot Type an input and press Enter Run Status code from OpenAI server Parameters ▼ Top-p (nucleus sampling) ↺ 0 1 Temperature ↺ 0 5 Número Checkbox User Consent for Data Collection, Use, and Sharing ▼ By using our app, which is powered by OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide: Collection: We may collect information, including the inputs you type into our app, the outputs generated by OpenAI's API, and certain technical details about your device and connection (such as browser type, operating system, and IP address) provided by your device's request headers. Use: We may use the collected data for research purposes, to improve our services, and to develop new products or services, including commercial applications, and for security purposes, such as protecting against unauthorized access and attacks. Sharing and Publication: Your data, including the technical details collected from your device's request headers, may be published, shared with third parties, or used for analysis and reporting purposes. Data Retention: We may retain your data, including the technical details collected from your device's request headers, for as long as necessary. By continuing to use our app, you provide your explicit consent to the collection, use, and potential sharing of your data as described above. If you do not agree with our data collection, use, and sharing practices, please do not use our app. I Agree Usar via API · Construído com Gradio · Configurações
Para clicar no botão "I Agree" dado o HTML que você forneceu (onde o botão tem uma classe lg secondary svelte-1ixn6qd e id dinâmico component-23 e não tem id fixo confiável), o ideal é buscar o botão por texto ou por alguma combinação de outros seletores, já que usar o id direto está dando erro (muito provavelmente por ser gerado dinamicamente).
Vou te mostrar uma forma robusta de buscar o botão "I Agree" e clicar nele antes de fazer o input, tentando de algumas formas: por XPath usando o texto do botão, por CSS selector usando a classe e depois como fallback por outros métodos.
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(driver, timeout=10):
wait = WebDriverWait(driver, timeout)
button = None
# Tente localizar pelo XPath pelo texto visível (mais confiável)
try:
print("Tentando clicar no botão 'I Agree' pelo XPath com texto...")
button = wait.until(
EC.element_to_be_clickable(
(By.XPATH, '//button[contains(normalize-space(.), "I Agree")]')
)
)
button.click()
print("Botão 'I Agree' clicado pelo XPath com texto.")
return True
except Exception as e:
print(f"Não encontrou botão 'I Agree' pelo XPath de texto: {e}")
# Tente localizar pelo CSS selector da classe, se souber alguma fixa (exemplo baseado no que você tem)
try:
print("Tentando clicar no botão 'I Agree' pelo CSS selector da classe...")
button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, 'button.lg.secondary.svelte-1ixn6qd')
)
)
button.click()
print("Botão 'I Agree' clicado pelo CSS selector da classe.")
return True
except Exception as e:
print(f"Não encontrou botão 'I Agree' pelo CSS selector da classe: {e}")
# Fallback: tente por texto parcial na tag span dentro do botão, caso texto não esteja diretamente no botão
try:
print("Tentando clicar no botão 'I Agree' pelo XPath com texto no span...")
button = wait.until(
EC.element_to_be_clickable(
(By.XPATH, '//button[descendant::span[contains(normalize-space(.), "I Agree")]]')
)
)
button.click()
print("Botão 'I Agree' clicado pelo XPath com texto no span.")
return True
except Exception as e:
print(f"Não conseguiu encontrar botão 'I Agree': {e}")
print("Botão 'I Agree' não foi encontrado.")
return False
quero o codigo completo
Claro! Vou integrar o código para detectar e clicar no botão "I Agree" (caso exista) antes de continuar com o input no textarea e clicar no "Run", mantendo a estrutura de conexão ao Chrome em modo debug e usando a aba já aberta.
Segue o código completo com essa lógica integrada:
Not yet included in a published release.
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 None
def 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
def abrir_aba_no_chrome(url):
try:
print("Inicializando webdriver com debug em 127.0.0.1:9222")
chrome_options = Options()
chrome_options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=chrome_options)
print(f"Navegando para a URL na aba existente: {url}")
driver.get(url)
wait = WebDriverWait(driver, 30)
# Aguarda até que pelo menos 1 iframe esteja presente na página
wait.until(lambda d: len(d.find_elements(By.TAG_NAME, 'iframe')) > 0)
print("Iframe(s) carregado(s).")
iframes = driver.find_elements(By.TAG_NAME, 'iframe')
print(f"Quantidade de iframes encontrados na página: {len(iframes)}")
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 encontrar textarea no 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. Erro: {e}")
if iframe_index_para_usar is None:
print("Textarea não encontrado em nenhum iframe, finalizando execução.")
driver.quit()
return False # sinaliza falha
# Volta para o iframe que possui o textarea
driver.switch_to.default_content()
driver.switch_to.frame(iframes[iframe_index_para_usar])
print("Preparando para digitar no textarea...")
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.")
# Pequena pausa para garantir o texto inserido - muito menor que antes
time.sleep(0.5)
run_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[normalize-space()="Run"]')))
run_button.click()
print("Botão 'Run' clicado, aguardando resposta do bot...")
ultima_msg = esperar_mensagem_bot(driver, timeout=30, poll_interval=1)
if ultima_msg:
print("Última mensagem do bot capturada com sucesso:", ultima_msg)
resultado = True
else:
print("Timeout: não foi possível capturar a última mensagem do bot.")
resultado = False
driver.quit()
return resultado
except Exception as err:
print(f"\nErro inesperado em abrir_aba_no_chrome: {err}")
traceback.print_exc()
try:
driver.quit()
except Exception:
pass
return False
def main():
try:
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.")
tentativas = 10
for i in range(1, tentativas + 1):
print(f"\n=== Tentativa {i} de {tentativas} ===")
sucesso = abrir_aba_no_chrome("https://huggingface.co/spaces/yuntian-deng/ChatGPT")
if sucesso:
print(f"Tentativa {i} finalizada com sucesso.")
else:
print(f"Tentativa {i} terminou com erro.")
time.sleep(3) # pequena pausa entre tentativas
print("Execução das tentativas finalizada.")
except Exception as e:
print("Erro fatal em main:", e)
traceback.print_exc()
if __name__ == "__main__":
main()
driver.execute_script(f"window.open('{url}', '_blank');")
driver.switch_to.window(driver.window_handles[-1])
driver.get(url)
para navegar diretamente na aba já conectada ao Chrome em modo debug.
Se precisar de mais alguma modificação é só pedir!
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)
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]
else:
print("Nenhuma mensagem válida encontrada.")
except Exception as ex:
print("Erro ao extrair mensagem do bot:", ex)
traceback.print_exc()
return None
def 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
def conectar_aba_existente_chrome(url_alvo):
try:
print("Inicializando webdriver com debug em 127.0.0.1:9222")
chrome_options = Options()
chrome_options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=chrome_options)
# Procura na lista de janelas/abas abertas a aba com a URL desejada
print("Verificando abas abertas para encontrar a URL alvo...")
encontrada = False
for handle in driver.window_handles:
driver.switch_to.window(handle)
atual_url = driver.current_url
print(f"Aba atual {handle} com URL: {atual_url}")
if url_alvo in atual_url:
print("Aba desejada encontrada!")
encontrada = True
break
if not encontrada:
print("Aba com a URL desejada não está aberta na sessão. Abortando.")
driver.quit()
return False
wait = WebDriverWait(driver, 30)
# Espera o iframe estar presente
wait.until(lambda d: len(d.find_elements(By.TAG_NAME, 'iframe')) > 0)
iframes = driver.find_elements(By.TAG_NAME, 'iframe')
print(f"Encontrados {len(iframes)} iframes na página.")
iframe_index_para_usar = None
for idx, iframe in enumerate(iframes):
try:
driver.switch_to.default_content()
driver.switch_to.frame(iframe)
print(f"Tentando encontrar textarea no iframe {idx}...")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'textarea[placeholder="Hi there!"]')))
iframe_index_para_usar = idx
print(f"Textarea encontrado no iframe {idx}")
break
except Exception as e:
print(f"Textarea não encontrado no iframe {idx}, tentando próximo. Erro: {e}")
if iframe_index_para_usar is None:
print("Textarea não encontrado em nenhum iframe, abortando.")
driver.quit()
return False
driver.switch_to.default_content()
driver.switch_to.frame(iframes[iframe_index_para_usar])
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 textarea.")
time.sleep(0.5) # garantia da digitação
run_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[normalize-space()="Run"]')))
run_button.click()
print("Botão 'Run' clicado, aguardando resposta...")
ultima_msg = esperar_mensagem_bot(driver, timeout=30)
if ultima_msg:
print(f"Última mensagem do bot capturada: {ultima_msg}")
else:
print("Não foi possível capturar a última mensagem do bot.")
driver.quit()
return True
except Exception as err:
print(f"Erro ao conectar e interagir com a aba existente: {err}")
traceback.print_exc()
try:
driver.quit()
except:
pass
return False
def main():
try:
if not chrome_debug_esta_rodando():
print("Chrome no modo debug não está rodando. Abrindo Chrome com modo debug.")
abrir_chrome_com_debug()
time.sleep(5) # aguarde um pouco para garantir que o Chrome iniciou
url_esp = "https://huggingface.co/spaces/yuntian-deng/ChatGPT"
sucesso = conectar_aba_existente_chrome(url_esp)
if sucesso:
print("Interação com aba existente concluída com sucesso.")
else:
print("Falha na interação com aba existente.")
except Exception as e:
print("Erro fatal em main:", e)
traceback.print_exc()
if __name__ == "__main__":
main()
url_alvo.Se quiser que o Chrome seja aberto dentro do próprio script (o que você não quer) ou que a aba seja aberta automaticamente, é só avisar, mas pelo que entendi seu objetivo é usar a aba existente.
Certifique-se de:
Abrir o Chrome manualmente com o comando (antes de rodar seu script):
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir=C:\temp\chrome-debug
Abrir manualmente a página https://huggingface.co/spaces/yuntian-deng/ChatGPT na aba.
Rodar esse script para ele conectar e interagir conforme pediu.
Se quiser posso ajudar a adaptar para manter o Chrome aberto depois da interação — só pedir!
# Assumindo que driver já está na aba correta
if clicar_botao_i_agree(driver):
print("Botão 'I Agree' detectado e clicado. Prosseguindo...")
else:
print("Botão 'I Agree' não foi encontrado - prosseguindo sem clicar...")
# Depois você pode continuar com a interação do textarea e Run normalmente
timeout do clicar_botao_i_agree(driver, timeout=10).driver.switch_to.frame(seu_iframe)
clicar_botao_i_agree(driver)
driver.switch_to.default_content()
Se quiser, posso adaptar esse código para ser integrado direto no seu script completo, é só avisar!
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)
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 clicar_botao_i_agree(driver, timeout=10):
wait = WebDriverWait(driver, timeout)
button = None
try:
print("Tentando clicar no botão 'I Agree' pelo XPath com texto...")
button = wait.until(
EC.element_to_be_clickable(
(By.XPATH, '//button[contains(normalize-space(.), "I Agree")]')
)
)
button.click()
print("Botão 'I Agree' clicado pelo XPath com texto.")
return True
except Exception as e:
print(f"Não encontrou botão 'I Agree' pelo XPath de texto: {e}")
try:
print("Tentando clicar no botão 'I Agree' pelo CSS selector da classe...")
button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, 'button.lg.secondary.svelte-1ixn6qd')
)
)
button.click()
print("Botão 'I Agree' clicado pelo CSS selector da classe.")
return True
except Exception as e:
print(f"Não encontrou botão 'I Agree' pelo CSS selector da classe: {e}")
try:
print("Tentando clicar no botão 'I Agree' pelo XPath com texto no span...")
button = wait.until(
EC.element_to_be_clickable(
(By.XPATH, '//button[descendant::span[contains(normalize-space(.), "I Agree")]]')
)
)
button.click()
print("Botão 'I Agree' clicado pelo XPath com texto no span.")
return True
except Exception as e:
print(f"Não conseguiu encontrar botão 'I Agree': {e}")
print("Botão 'I Agree' não foi encontrado.")
return False
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]
else:
print("Nenhuma mensagem válida encontrada.")
except Exception as ex:
print("Erro ao extrair mensagem do bot:", ex)
traceback.print_exc()
return None
def 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
def conectar_aba_existente_chrome(url_alvo):
try:
print("Inicializando webdriver com debug em 127.0.0.1:9222")
chrome_options = Options()
chrome_options.debugger_address = "127.0.0.1:9222"
driver = webdriver.Chrome(options=chrome_options)
print("Verificando abas abertas para encontrar a URL alvo...")
encontrada = False
for handle in driver.window_handles:
driver.switch_to.window(handle)
atual_url = driver.current_url
print(f"Aba atual {handle} com URL: {atual_url}")
if url_alvo in atual_url:
print("Aba desejada encontrada!")
encontrada = True
break
if not encontrada:
print("Aba com a URL desejada não está aberta na sessão. Abortando.")
driver.quit()
return False
# Tentar clicar no botão "I Agree" caso apareça
if clicar_botao_i_agree(driver):
print("Consentimento fornecido, botão 'I Agree' clicado.")
# aguarde um pouco para a página atualizar/avançar após clique
time.sleep(2)
else:
print("Botão 'I Agree' não encontrado, pulando consentimento.")
wait = WebDriverWait(driver, 30)
wait.until(lambda d: len(d.find_elements(By.TAG_NAME, 'iframe')) > 0)
iframes = driver.find_elements(By.TAG_NAME, 'iframe')
print(f"Encontrados {len(iframes)} iframes na página.")
iframe_index_para_usar = None
for idx, iframe in enumerate(iframes):
try:
driver.switch_to.default_content()
driver.switch_to.frame(iframe)
print(f"Tentando encontrar textarea no iframe {idx}...")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'textarea[placeholder="Hi there!"]')))
iframe_index_para_usar = idx
print(f"Textarea encontrado no iframe {idx}")
break
except Exception as e:
print(f"Textarea não encontrado no iframe {idx}, tentando próximo. Erro: {e}")
if iframe_index_para_usar is None:
print("Textarea não encontrado em nenhum iframe, abortando.")
driver.quit()
return False
driver.switch_to.default_content()
driver.switch_to.frame(iframes[iframe_index_para_usar])
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 textarea.")
time.sleep(0.5) # garantia da digitação
run_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[normalize-space()="Run"]')))
run_button.click()
print("Botão 'Run' clicado, aguardando resposta...")
ultima_msg = esperar_mensagem_bot(driver, timeout=30)
if ultima_msg:
print(f"Última mensagem do bot capturada: {ultima_msg}")
else:
print("Não foi possível capturar a última mensagem do bot.")
driver.quit()
return True
except Exception as err:
print(f"Erro ao conectar e interagir com a aba existente: {err}")
traceback.print_exc()
try:
driver.quit()
except:
pass
return False
def main():
try:
if not chrome_debug_esta_rodando():
print("Chrome no modo debug não está rodando. Abrindo Chrome com modo debug.")
abrir_chrome_com_debug()
# aguarde para garantir que abriu antes de conectar
time.sleep(5)
url_esp = "https://huggingface.co/spaces/yuntian-deng/ChatGPT"
sucesso = conectar_aba_existente_chrome(url_esp)
if sucesso:
print("Interação com aba existente concluída com sucesso.")
else:
print("Falha na interação com aba existente.")
except Exception as e:
print("Erro fatal em main:", e)
traceback.print_exc()
if __name__ == "__main__":
main()
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir=C:\temp\chrome-debug
Abra manualmente a página https://huggingface.co/spaces/yuntian-deng/ChatGPT e, se aparecer, o botão "I Agree".
Rode o script. Ele vai detectar a aba aberta, clicar no botão "I Agree" se existir, depois digitar "oi" no textarea, clicar em "Run" e imprimir a resposta no terminal.
Se surgir algum erro ou precisar de ajuste para iframe no botão "I Agree" (caso ele esteja dentro de algum iframe), me fale que te ajudo a adaptar!