feat: add persistent browser utility for session management and improve RPA element interaction logging and robustness

This commit is contained in:
2026-05-31 23:59:59 -06:00
parent b366d914a4
commit 43d37f0f0a
2 changed files with 63 additions and 4 deletions

View File

@@ -487,7 +487,7 @@ class SigaAutomation:
async def validate_and_enter_month(self):
page = self.page
now = datetime.now()
now = datetime.now() #- timedelta(days=1)
month_text = f"Mês de Trabalho {now.month:02d}/{now.year}"
month_link = page.get_by_role("link", name=month_text)
@@ -601,6 +601,9 @@ class SigaAutomation:
await human_delay(150, 350)
# Localiza todas as células do mês atual (sem .old e sem .new)
# prev_month = dp.locator(".icon-arrow-left")
# await mouse.click_element(prev_month)
# await human_delay(250, 550)
cells = dp.locator("td.day:not(.old):not(.new)")
count = await cells.count()
@@ -675,7 +678,9 @@ class SigaAutomation:
# Estratégia 1: texto exato
try:
exact = page.locator("#select2-drop").get_by_text(code, exact=True)
logger.info(f" Buscando {code_upper} no catalogo.")
if await exact.count() > 0 and await exact.first.is_visible(timeout=2000):
logger.info(f" ✅ {code_upper} encontrado.")
await mouse.click_element(exact.first)
return True
except Exception:
@@ -711,9 +716,15 @@ class SigaAutomation:
async def _cancel_saida(self):
cancel = self.page.locator(
'button.btn.btn-link.no-border[data-dismiss="modal"]',
has_text="Cancelar",
)
'button.btn.btn-link').get_by_text("Cancelar", exact=True)
mouse = self.mouse
cancel_box = await cancel.bounding_box()
if cancel_box:
await mouse.move_to(
cancel_box["x"] + cancel_box["width"] / 2,
cancel_box["y"] - 20,
)
await human_delay(150, 350)
await self.mouse.click_element(cancel)
await human_delay(1000, 2000)
logger.info("🚫 SAÍDA cancelada.")

48
open_browser.py Normal file
View File

@@ -0,0 +1,48 @@
import asyncio
import os
from playwright.async_api import async_playwright
async def main():
playwright = await async_playwright().start()
project_root = os.path.dirname(os.path.abspath(__file__))
user_data_dir = os.path.join(project_root, "perfil_chromium")
print(f"\n============================================================")
print(f"INICIANDO CHROMIUM COM PERFIL PERSISTENTE")
print(f"Perfil: {user_data_dir}")
print(f"============================================================\n")
print("-> O navegador foi aberto na pagina do SIGA.")
print("-> Voce pode fazer login, resolver o reCAPTCHA ou salvar sessoes a vontade.")
print("-> Para fechar, basta fechar a janela do navegador ou pressionar Ctrl+C aqui no terminal.\n")
context = await playwright.chromium.launch_persistent_context(
user_data_dir=user_data_dir,
headless=False,
user_agent=(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/124.0.0.0 Safari/537.36"
),
args=["--disable-blink-features=AutomationControlled"],
ignore_default_args=["--enable-automation"],
viewport={"width": 1366, "height": 768},
locale="pt-BR",
timezone_id="America/Cuiaba",
)
page = context.pages[0] if context.pages else await context.new_page()
await page.goto("https://siga.congregacao.org.br/index.aspx")
# Mantem o script rodando enquanto o navegador estiver aberto
try:
while len(context.pages) > 0:
await asyncio.sleep(1)
except (KeyboardInterrupt, asyncio.CancelledError):
pass
finally:
await context.close()
await playwright.stop()
print("\n[INFO] Navegador fechado e recursos liberados.")
if __name__ == "__main__":
asyncio.run(main())