#! /bin/env python3 import sys import os import time as tm from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
mouse#
from selenium.webdriver.common.action_chains import ActionChains import html2text
proxy = “socks5://127.0.0.1:9050”
Configurando o navegador#
options = Options()
options.add_argument(’–headless’) # Execução em modo headless (sem interface gráfica)#
options.add_argument(’–disable-gpu’) # Desabilita a aceleração de GPU options.add_argument(’–disable-background-timer-throttling’) options.add_argument(’–disable-backgrounding-occluded-windows’) options.add_argument("–incognito")
if os.getenv(‘TOR’) == ‘yes’: options.add_argument(f’–proxy-server={proxy}’)
DEBUG = False
if os.getenv(‘DEBUG’) == ‘yes’: DEBUG = True
chrome_driver_path = ‘/opt/ungoogled_chromium/usr/lib/chromium/chromedriver’#
chrome_driver_path = ‘/usr/bin/chromedriver’ service = Service(chrome_driver_path) driver = webdriver.Chrome(service=service, options=options) driver.maximize_window() actions = ActionChains(driver)
Configurações:#
duckduck_ia_chat=‘https://duckduckgo.com/ia=%20?ia=chat' link_chatgpt=‘https://chatgpt.com/' link_chatgpt=duckduck_ia_chat
Funções:#
def func_save_page(driver): f = open(’/tmp/pag.html’, ‘w’) f.write(str(driver.page_source)) f.close()
def func_interage(driver, pergunta=’ ‘, contador=1, par_uma_vez=False): #atrib_campo_iteracao=’//*[@id=“react-layout”]/div/div[2]/main/div/section[2]/div/div/form/div[1]/div[2]/textarea’ atrib_campo_iteracao=’//textarea[@name=“user-prompt”]’ field_chat = driver.find_element(By.XPATH, atrib_campo_iteracao)
if DEBUG: sys.stderr.write('\n\t--1\n')
# Envia uma pergunta
# if contador == 1:
# pergunta='sempre responda em portugues'
# if DEBUG: sys.stderr.write("pergunta padão")
if DEBUG: sys.stderr.write(pergunta)
field_chat.send_keys(pergunta)
if DEBUG: sys.stderr.write('\n\t--2\n')
# tm.sleep(1)
# atrib_button_send='//button[@aria-label]'
atrib_button_send='//button[@type="submit"]'
# atrib_button_send='//*[@id="react-layout"]/div/div[2]/main/div/section[2]/div/div/form/div[1]/div[3]/button'
tm.sleep(0.2)
try:
button_to_click = driver.find_element(By.XPATH, atrib_button_send)
except:
if DEBUG: sys.stderr.write(f'Não encontrado: {atrib_button_send}')
if DEBUG: sys.stderr.write('\n\t--3\n')
actions.move_to_element(button_to_click)
tm.sleep(1)
actions.click().perform()
# actions.move_to_element(button_to_click).double_click().perform()
if DEBUG: sys.stderr.write('\n\ttestei clicar!!\n')
# respostas Bolinha esquerda
# atrib_new_resp = f'//*[@id="react-layout"]/div/div[2]/main/div/section[2]/div/div/div/div[{contador}]/div[2]/div[1]/div/div'
if contador == 1:
atrib_new_resp = f'//*[@id="react-layout"]/div/div[2]/main/div/section[2]/div/div/div/div/div[2]/div[2]/div'
else:
atrib_new_resp = f'//*[@id="react-layout"]/div/div[2]/main/div/section[2]/div/div/div/div[{contador}]/div[2]/div[2]/div'
try:
if DEBUG: sys.stderr.write("\n\tAguardando...\n")
# Aguarda o processamento da resposta:
button_stop_process ='//button[@aria-label="Parar"]'
# Aguarda o processamento da resposta:
WebDriverWait(driver, 40).until(EC.invisibility_of_element((By.XPATH, button_stop_process)))
button_stop_process ='//button[@aria-label="Stop"]'
WebDriverWait(driver, 40).until(EC.invisibility_of_element((By.XPATH, button_stop_process)))
# func_presence(driver, button_stop_process )
if DEBUG: sys.stderr.write("\n\tPronto... \n")
except:
if DEBUG: sys.stderr.write(f'\nNão encontrei {button_stop_process}\n\t')
# Mostra a resposta
respostas_chat = driver.find_element(By.XPATH, atrib_new_resp)
div_html = respostas_chat.get_attribute('outerHTML')
markdown_content = html2text.html2text(str(div_html))
print('\n\n' + markdown_content)
MSG01='''
[#] - Para sair
[@] - Entradas com \'\\n\'
Para sair \'@\'
ou
Nova pergunta:
_ ’’’
if par_uma_vez == True:
if DEBUG: sys.stderr.write("\nExecutando uma vez\n")
return 0
sys.stderr.write(f'\n{MSG01}')
nova_pergunta = input()
if nova_pergunta == '@':
temp = " "
texto_com_newline = ' '
while temp != "@":
texto_com_newline = texto_com_newline + ' ' + temp
temp = input().replace('\n', ' ')
if DEBUG: sys.stderr.write(f'\n{texto_com_newline}\n')
func_interage(driver, texto_com_newline, contador=contador +1 )
elif nova_pergunta != '#':
func_interage(driver, nova_pergunta, contador=contador +1 )
else:
if DEBUG: sys.stderr.write("\n\tSessão terminada\n\t")
return 0
def mostrar_exemplo():
print(f"\nExemplo de uso:\n python {sys.argv[0]} <opções>
Inicializa as variáveis#
par_uma_vez = False par_conteudo = ‘Olá, responda sempre em português’ # Valor padrão
try: if len(sys.argv) == 1: par_conteudo = ‘Olá, responda sempre em português’ # Valor padrão
# Verificar se sys.argv[1] existe
elif len(sys.argv) > 1:
if sys.argv[1].lower() in ['1', 'sim', 's']:
par_uma_vez = True
else:
print("Condição não atendida, exibindo o exemplo...")
mostrar_exemplo() # Exibe o exemplo e finaliza o script
# sys.exit(1) # Finaliza o script com código de erro (opcional)
par_uma_vez = True
par_conteudo = sys.argv[1]
else:
print("Erro: Argumento necessário!")
mostrar_exemplo() # Exibe o exemplo e finaliza o script
sys.exit(1) # Finaliza o script com código de erro (opcional)
# Verificar se há um segundo argumento opcional
if len(sys.argv) > 2:
par_conteudo = sys.argv[2]
except IndexError as e: # Se houver um erro de índice, exibe o exemplo print(f"Erro ao acessar argumento: {e}") mostrar_exemplo()
except Exception as e: # Captura qualquer outra exceção não esperada print(f"Erro inesperado: {e}") mostrar_exemplo()
driver.get(link_chatgpt )
Campo de iteração:#
atrib_campo_iteracao=’//p[@data-placeholder]’#
atrib_start_duck_gpt=’//button[@tabindex=“1”]’
atrb_init_chat = [ ‘//[@id=“react-layout”]/div/div[2]/main/div/div/div[2]/div/button’ ,’//[@id=“react-layout”]/div/div[2]/main/div/div/div[3]/div/button’ ,’//*[@id=“react-layout”]/div/div[2]/main/div/div/div[4]/div/div[2]/button’ ]
try: if DEBUG: sys.stderr.write(f’\nIniciando o navegador{par_conteudo}\n’) tm.sleep(0.1)
try:
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH,
atrb_init_chat[0])))
except:
if DEBUG: sys.stderr.write('\nProblemas \n')
for atrb_atual in atrb_init_chat:
try:
button_to_click = driver.find_element(By.XPATH,
atrb_atual )
actions.move_to_element(button_to_click).click().perform()
tm.sleep(0.1)
except:
if DEBUG: sys.stderr.write('\nProblema antes de chamar a função principal\n')
if DEBUG: sys.stderr.write('\nChamando a função\n')
func_interage(driver, par_conteudo, par_uma_vez=par_uma_vez)
if DEBUG: sys.stderr.write('\nfunção executada!\n')
except Exception as e: if DEBUG: sys.stderr.write(f’\nException na primeira chamada\n\n{e} ‘)
if DEBUG: if input(“Deseja fechar a janela? : (N/s)”) == ’s’ : print(‘ok’)
driver.quit() sys.exit()