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+
import re
|
| 3 |
+
from typing import Dict, Optional
|
| 4 |
+
|
| 5 |
+
from playwright.sync_api import sync_playwright
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class AutomationConfig:
|
| 10 |
+
url: str
|
| 11 |
+
pre_submit_delay: float = 1.0
|
| 12 |
+
headless: bool = True
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def norm(s: str) -> str:
|
| 16 |
+
s = (s or '').lower().strip()
|
| 17 |
+
table = str.maketrans('áàãâäéèêëíìîïóòõôöúùûüç', 'aaaaaeeeeiiiiooooouuuuc')
|
| 18 |
+
s = s.translate(table)
|
| 19 |
+
s = re.sub(r'\s+', ' ', s)
|
| 20 |
+
return s
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def candidate_text(locator) -> str:
|
| 24 |
+
parts = []
|
| 25 |
+
for attr in ('aria-label', 'placeholder', 'name', 'id', 'type'):
|
| 26 |
+
try:
|
| 27 |
+
v = locator.get_attribute(attr)
|
| 28 |
+
if v:
|
| 29 |
+
parts.append(v)
|
| 30 |
+
except Exception:
|
| 31 |
+
pass
|
| 32 |
+
return norm(' '.join(parts))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SPXAutomation:
|
| 36 |
+
def __init__(self, config: AutomationConfig):
|
| 37 |
+
self.config = config
|
| 38 |
+
|
| 39 |
+
def _fill_best_match(self, page, value: str, aliases: list[str]) -> Optional[str]:
|
| 40 |
+
if not value:
|
| 41 |
+
return None
|
| 42 |
+
wanted = [norm(x) for x in aliases]
|
| 43 |
+
|
| 44 |
+
for alias in wanted:
|
| 45 |
+
try:
|
| 46 |
+
loc = page.get_by_label(alias, exact=False).first
|
| 47 |
+
if loc.count() and loc.is_visible():
|
| 48 |
+
loc.fill(value)
|
| 49 |
+
return alias
|
| 50 |
+
except Exception:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
controls = page.locator('input:not([type="hidden"]), textarea, select')
|
| 54 |
+
try:
|
| 55 |
+
count = controls.count()
|
| 56 |
+
except Exception:
|
| 57 |
+
count = 0
|
| 58 |
+
|
| 59 |
+
for i in range(count):
|
| 60 |
+
c = controls.nth(i)
|
| 61 |
+
try:
|
| 62 |
+
if not c.is_visible():
|
| 63 |
+
continue
|
| 64 |
+
meta = candidate_text(c)
|
| 65 |
+
if any(a in meta or meta in a for a in wanted):
|
| 66 |
+
typ = (c.get_attribute('type') or '').lower()
|
| 67 |
+
if typ in ('radio', 'checkbox', 'file'):
|
| 68 |
+
continue
|
| 69 |
+
c.fill(value)
|
| 70 |
+
return meta or wanted[0]
|
| 71 |
+
except Exception:
|
| 72 |
+
continue
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
def _discover_embedded_frame(self, page):
|
| 76 |
+
for frame in page.frames:
|
| 77 |
+
try:
|
| 78 |
+
if frame.locator('input, textarea, select').count() > 0:
|
| 79 |
+
return frame
|
| 80 |
+
except Exception:
|
| 81 |
+
pass
|
| 82 |
+
return page
|
| 83 |
+
|
| 84 |
+
def fill_and_submit(self, profile: Dict[str, str]) -> str:
|
| 85 |
+
aliases = {
|
| 86 |
+
'nome': ['nome', 'nome completo', 'seu nome'],
|
| 87 |
+
'cpf': ['cpf'],
|
| 88 |
+
'telefone': ['telefone', 'celular', 'whatsapp'],
|
| 89 |
+
'email': ['email', 'e-mail'],
|
| 90 |
+
'cidade': ['cidade', 'municipio', 'município'],
|
| 91 |
+
'cep': ['cep'],
|
| 92 |
+
'disponibilidade': ['disponibilidade', 'dias disponiveis', 'dias disponíveis', 'disponível'],
|
| 93 |
+
'hub': ['hub', 'unidade'],
|
| 94 |
+
'observacao': ['observacao', 'observação', 'obs'],
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
with sync_playwright() as p:
|
| 98 |
+
browser = p.chromium.launch(headless=self.config.headless)
|
| 99 |
+
context = browser.new_context(viewport={'width': 1365, 'height': 900})
|
| 100 |
+
page = context.new_page()
|
| 101 |
+
try:
|
| 102 |
+
page.goto(self.config.url, wait_until='domcontentloaded', timeout=60000)
|
| 103 |
+
page.wait_for_timeout(2500)
|
| 104 |
+
frame = self._discover_embedded_frame(page)
|
| 105 |
+
|
| 106 |
+
filled = []
|
| 107 |
+
missing = []
|
| 108 |
+
for key, value in profile.items():
|
| 109 |
+
if not value:
|
| 110 |
+
continue
|
| 111 |
+
matched = self._fill_best_match(frame, value, aliases.get(key, [key]))
|
| 112 |
+
if matched:
|
| 113 |
+
filled.append(key)
|
| 114 |
+
else:
|
| 115 |
+
missing.append(key)
|
| 116 |
+
|
| 117 |
+
page.wait_for_timeout(int(max(0, self.config.pre_submit_delay) * 1000))
|
| 118 |
+
|
| 119 |
+
submit_candidates = [
|
| 120 |
+
frame.get_by_role('button', name=re.compile(r'enviar|submit|registrar|confirmar|salvar', re.I)),
|
| 121 |
+
frame.locator('input[type="submit"]'),
|
| 122 |
+
frame.locator('button[type="submit"]'),
|
| 123 |
+
]
|
| 124 |
+
submit = None
|
| 125 |
+
for cand in submit_candidates:
|
| 126 |
+
try:
|
| 127 |
+
count = cand.count()
|
| 128 |
+
if count > 0:
|
| 129 |
+
for idx in range(min(count, 3)):
|
| 130 |
+
el = cand.nth(idx)
|
| 131 |
+
if el.is_visible() and el.is_enabled():
|
| 132 |
+
submit = el
|
| 133 |
+
break
|
| 134 |
+
if submit:
|
| 135 |
+
break
|
| 136 |
+
except Exception:
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
if not submit:
|
| 140 |
+
raise RuntimeError(
|
| 141 |
+
f'Botão de envio não localizado. Campos preenchidos: {", ".join(filled) or "nenhum"}. '
|
| 142 |
+
f'Não encontrados: {", ".join(missing) if missing else "nenhum"}.'
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
submit.click()
|
| 146 |
+
page.wait_for_timeout(2500)
|
| 147 |
+
|
| 148 |
+
return (
|
| 149 |
+
f'Campos preenchidos: {", ".join(filled) or "nenhum"}. '
|
| 150 |
+
f'Não encontrados: {", ".join(missing) if missing else "nenhum"}. '
|
| 151 |
+
f'URL final: {page.url}'
|
| 152 |
+
)
|
| 153 |
+
finally:
|
| 154 |
+
context.close()
|
| 155 |
+
browser.close()
|