import time
import imaplib
import email
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from email.header import decode_header
# Função para aceitar cookies
def accept_cookies(driver):
try:
cookie_button = driver.find_element(By.XPATH,
"//button[contains(text(), 'Accept')]" or "//button[contains(text(),
'Aceitar')]")
if cookie_button.is_displayed():
cookie_button.click()
print("Cookies aceitos com sucesso.")
except Exception as e:
print("Botão de cookies não encontrado ou já aceito.", str(e))
# Função para realizar login
def login(driver, credentials):
try:
driver.get("https://visa.vfsglobal.com/ago/en/prt/login")
time.sleep(3)
username_field = driver.find_element(By.CSS_SELECTOR, "#email")
password_field = driver.find_element(By.CSS_SELECTOR,
"#password")
login_button = driver.find_element(By.XPATH,
"//button[@type='submit']")
username_field.send_keys(credentials['username'])
password_field.send_keys(credentials['password'])
login_button.click()
print("Login realizado com sucesso.")
time.sleep(5)
except Exception as e:
print("Erro durante o login.", str(e))
# Função para capturar e inserir códigos OTP
def handle_otp(driver, otp_code):
try:
otp_field = driver.find_element(By.CSS_SELECTOR, "#otp-input") #
Substituir pelo seletor real
if otp_field:
otp_field.clear()
otp_field.send_keys(otp_code)
otp_field.send_keys(Keys.RETURN)
print("Código OTP inserido com sucesso.")
except Exception as e:
print("Erro ao inserir o código OTP.", str(e))
# Função para capturar o OTP do Gmail
def get_otp_from_gmail(email_user, email_password):
try:
# Conectar ao servidor IMAP do Gmail
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(email_user, email_password)
mail.select("inbox")
# Buscar os e-mails mais recentes
status, messages = mail.search(None, "UNSEEN")
mail_ids = messages[0].split()
for mail_id in reversed(mail_ids):
# Obter o e-mail
status, msg_data = mail.fetch(mail_id, "(RFC822)")
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1])
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding or "utf-8")
# Verificar se o e-mail é relacionado ao OTP
if "OTP" in subject:
print(f"Email encontrado: {subject}")
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True).decode()
otp = extract_otp(body)
return otp
else:
body = msg.get_payload(decode=True).decode()
otp = extract_otp(body)
return otp
print("Nenhum e-mail com OTP encontrado.")
return None
except Exception as e:
print("Erro ao capturar o OTP do Gmail.", str(e))
return None
# Função auxiliar para extrair o OTP do corpo do e-mail
def extract_otp(body):
import re
match = re.search(r"\b\d{6}\b", body) # Ajustar para o formato do OTP
(6 dígitos)
return match.group(0) if match else None
# Função principal
def main():
# Configuração para o ChromeDriver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Credenciais de login no site
login_credentials = {
'username': "[email protected]",
'password': "suasenha"
# Credenciais de acesso ao Gmail
gmail_credentials = {
'email_user': "[email protected]",
'email_password': "suasenhaouappsenha"
}
# Realizar login no site
login(driver, login_credentials)
# Aceitar cookies
accept_cookies(driver)
# Capturar o código OTP automaticamente
otp_code = get_otp_from_gmail(gmail_credentials['email_user'],
gmail_credentials['email_password'])
if otp_code:
handle_otp(driver, otp_code)
else:
print("Não foi possível capturar o OTP.")
driver.quit()
if __name__ == "__main__":
main()