Spaces:
Paused
Paused
Download automation.py from Automacaospx/spx: direct link, hf CLI and curl.
- Browser
- Download file 5.5 kB
-
https://huggingface.co/spaces/Automacaospx/spx/resolve/main/automation.py
- Command line
-
hf download hf://spaces/Automacaospx/spx/automation.py
-
curl -L -o automation.py https://huggingface.co/spaces/Automacaospx/spx/resolve/main/automation.py
5.5 kB
| from dataclasses import dataclass | |
| import re | |
| from typing import Dict, Optional | |
| from playwright.sync_api import sync_playwright | |
| class AutomationConfig: | |
| url: str | |
| pre_submit_delay: float = 1.0 | |
| headless: bool = True | |
| def norm(s: str) -> str: | |
| s = (s or '').lower().strip() | |
| table = str.maketrans('áàãâäéèêëíìîïóòõôöúùûüç', 'aaaaaeeeeiiiiooooouuuuc') | |
| s = s.translate(table) | |
| s = re.sub(r'\s+', ' ', s) | |
| return s | |
| def candidate_text(locator) -> str: | |
| parts = [] | |
| for attr in ('aria-label', 'placeholder', 'name', 'id', 'type'): | |
| try: | |
| v = locator.get_attribute(attr) | |
| if v: | |
| parts.append(v) | |
| except Exception: | |
| pass | |
| return norm(' '.join(parts)) | |
| class SPXAutomation: | |
| def __init__(self, config: AutomationConfig): | |
| self.config = config | |
| def _fill_best_match(self, page, value: str, aliases: list[str]) -> Optional[str]: | |
| if not value: | |
| return None | |
| wanted = [norm(x) for x in aliases] | |
| for alias in wanted: | |
| try: | |
| loc = page.get_by_label(alias, exact=False).first | |
| if loc.count() and loc.is_visible(): | |
| loc.fill(value) | |
| return alias | |
| except Exception: | |
| pass | |
| controls = page.locator('input:not([type="hidden"]), textarea, select') | |
| try: | |
| count = controls.count() | |
| except Exception: | |
| count = 0 | |
| for i in range(count): | |
| c = controls.nth(i) | |
| try: | |
| if not c.is_visible(): | |
| continue | |
| meta = candidate_text(c) | |
| if any(a in meta or meta in a for a in wanted): | |
| typ = (c.get_attribute('type') or '').lower() | |
| if typ in ('radio', 'checkbox', 'file'): | |
| continue | |
| c.fill(value) | |
| return meta or wanted[0] | |
| except Exception: | |
| continue | |
| return None | |
| def _discover_embedded_frame(self, page): | |
| for frame in page.frames: | |
| try: | |
| if frame.locator('input, textarea, select').count() > 0: | |
| return frame | |
| except Exception: | |
| pass | |
| return page | |
| def fill_and_submit(self, profile: Dict[str, str]) -> str: | |
| aliases = { | |
| 'nome': ['nome', 'nome completo', 'seu nome'], | |
| 'cpf': ['cpf'], | |
| 'telefone': ['telefone', 'celular', 'whatsapp'], | |
| 'email': ['email', 'e-mail'], | |
| 'cidade': ['cidade', 'municipio', 'município'], | |
| 'cep': ['cep'], | |
| 'disponibilidade': ['disponibilidade', 'dias disponiveis', 'dias disponíveis', 'disponível'], | |
| 'hub': ['hub', 'unidade'], | |
| 'observacao': ['observacao', 'observação', 'obs'], | |
| } | |
| with sync_playwright() as p: | |
| browser = p.chromium.launch(headless=self.config.headless) | |
| context = browser.new_context(viewport={'width': 1365, 'height': 900}) | |
| page = context.new_page() | |
| try: | |
| page.goto(self.config.url, wait_until='domcontentloaded', timeout=60000) | |
| page.wait_for_timeout(2500) | |
| frame = self._discover_embedded_frame(page) | |
| filled = [] | |
| missing = [] | |
| for key, value in profile.items(): | |
| if not value: | |
| continue | |
| matched = self._fill_best_match(frame, value, aliases.get(key, [key])) | |
| if matched: | |
| filled.append(key) | |
| else: | |
| missing.append(key) | |
| page.wait_for_timeout(int(max(0, self.config.pre_submit_delay) * 1000)) | |
| submit_candidates = [ | |
| frame.get_by_role('button', name=re.compile(r'enviar|submit|registrar|confirmar|salvar', re.I)), | |
| frame.locator('input[type="submit"]'), | |
| frame.locator('button[type="submit"]'), | |
| ] | |
| submit = None | |
| for cand in submit_candidates: | |
| try: | |
| count = cand.count() | |
| if count > 0: | |
| for idx in range(min(count, 3)): | |
| el = cand.nth(idx) | |
| if el.is_visible() and el.is_enabled(): | |
| submit = el | |
| break | |
| if submit: | |
| break | |
| except Exception: | |
| pass | |
| if not submit: | |
| raise RuntimeError( | |
| f'Botão de envio não localizado. Campos preenchidos: {", ".join(filled) or "nenhum"}. ' | |
| f'Não encontrados: {", ".join(missing) if missing else "nenhum"}.' | |
| ) | |
| submit.click() | |
| page.wait_for_timeout(2500) | |
| return ( | |
| f'Campos preenchidos: {", ".join(filled) or "nenhum"}. ' | |
| f'Não encontrados: {", ".join(missing) if missing else "nenhum"}. ' | |
| f'URL final: {page.url}' | |
| ) | |
| finally: | |
| context.close() | |
| browser.close() | |