Conseguiu entrar no formulario e datepicker
This commit is contained in:
@@ -3,10 +3,14 @@
|
|||||||
Fundo Bíblico RPA - Automação de Lançamentos no SIGA
|
Fundo Bíblico RPA - Automação de Lançamentos no SIGA
|
||||||
Lê vendas do Google Sheets, agrupa por dia+meio de pagamento,
|
Lê vendas do Google Sheets, agrupa por dia+meio de pagamento,
|
||||||
e lança como SAÍDAs no sistema SIGA via Playwright.
|
e lança como SAÍDAs no sistema SIGA via Playwright.
|
||||||
|
|
||||||
|
Anti-bot: movimentos humanos de mouse, delays variáveis, jitter.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
import math
|
||||||
import os
|
import os
|
||||||
|
import random
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, date, timedelta
|
from datetime import datetime, date, timedelta
|
||||||
@@ -59,7 +63,6 @@ class Config:
|
|||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
@dataclass
|
@dataclass
|
||||||
class SaleItem:
|
class SaleItem:
|
||||||
"""Uma venda individual da planilha."""
|
|
||||||
id: int
|
id: int
|
||||||
data_venda: date
|
data_venda: date
|
||||||
item_code: str
|
item_code: str
|
||||||
@@ -70,7 +73,6 @@ class SaleItem:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class AggregatedProduct:
|
class AggregatedProduct:
|
||||||
"""Produto agregado (mesmo código) dentro de um grupo."""
|
|
||||||
code: str
|
code: str
|
||||||
total_qty: int
|
total_qty: int
|
||||||
total_valor: float
|
total_valor: float
|
||||||
@@ -79,7 +81,6 @@ class AggregatedProduct:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class SaleGroup:
|
class SaleGroup:
|
||||||
"""Grupo de vendas agrupado por data + meio de pagamento."""
|
|
||||||
data_venda: date
|
data_venda: date
|
||||||
meio_pag: str
|
meio_pag: str
|
||||||
items: List[SaleItem] = field(default_factory=list)
|
items: List[SaleItem] = field(default_factory=list)
|
||||||
@@ -109,7 +110,6 @@ class SaleGroup:
|
|||||||
# UTILITÁRIOS
|
# UTILITÁRIOS
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
def parse_date(date_val) -> Optional[date]:
|
def parse_date(date_val) -> Optional[date]:
|
||||||
"""Converte diversos formatos de data do Google Sheets para date."""
|
|
||||||
if date_val is None:
|
if date_val is None:
|
||||||
return None
|
return None
|
||||||
if isinstance(date_val, (int, float)):
|
if isinstance(date_val, (int, float)):
|
||||||
@@ -138,8 +138,6 @@ def parse_date(date_val) -> Optional[date]:
|
|||||||
# GOOGLE SHEETS SERVICE
|
# GOOGLE SHEETS SERVICE
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
class GoogleSheetsService:
|
class GoogleSheetsService:
|
||||||
"""Leitura/escrita no Google Sheets via Service Account."""
|
|
||||||
|
|
||||||
def __init__(self, credentials_file: str, spreadsheet_id: str):
|
def __init__(self, credentials_file: str, spreadsheet_id: str):
|
||||||
scopes = [
|
scopes = [
|
||||||
"https://www.googleapis.com/auth/spreadsheets",
|
"https://www.googleapis.com/auth/spreadsheets",
|
||||||
@@ -155,7 +153,6 @@ class GoogleSheetsService:
|
|||||||
def read_vendas(self, target_month: int, target_year: int) -> List[SaleItem]:
|
def read_vendas(self, target_month: int, target_year: int) -> List[SaleItem]:
|
||||||
records = self.vendas_ws.get_all_records()
|
records = self.vendas_ws.get_all_records()
|
||||||
sales: List[SaleItem] = []
|
sales: List[SaleItem] = []
|
||||||
|
|
||||||
for rec in records:
|
for rec in records:
|
||||||
try:
|
try:
|
||||||
dt = parse_date(rec.get("DataVenda"))
|
dt = parse_date(rec.get("DataVenda"))
|
||||||
@@ -221,11 +218,157 @@ def group_sales(sales: List[SaleItem], launched_ids: Set[int]) -> List[SaleGroup
|
|||||||
return groups
|
return groups
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# MÓDULO ANTI-BOT — Movimentos humanos de mouse
|
||||||
|
# ==============================================================================
|
||||||
|
class HumanMouse:
|
||||||
|
"""
|
||||||
|
Simula comportamento humano de mouse:
|
||||||
|
- Trajetória curva (Bézier quadrática) entre dois pontos
|
||||||
|
- Microtremores (jitter) ao longo do caminho
|
||||||
|
- Velocidade variável com aceleração/desaceleração (ease-in-out)
|
||||||
|
- Pausas aleatórias antes/depois do clique
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, page: Page):
|
||||||
|
self.page = page
|
||||||
|
# Posição corrente estimada (começa no centro da tela)
|
||||||
|
self._x = 640.0
|
||||||
|
self._y = 400.0
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Helpers internos
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _ease_in_out(t: float) -> float:
|
||||||
|
"""Curva de aceleração suave: devagar → rápido → devagar."""
|
||||||
|
return t * t * (3.0 - 2.0 * t)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _bezier(t: float, p0: tuple, p1: tuple, p2: tuple) -> tuple:
|
||||||
|
"""Ponto na curva Bézier quadrática em t ∈ [0, 1]."""
|
||||||
|
x = (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t ** 2 * p2[0]
|
||||||
|
y = (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t ** 2 * p2[1]
|
||||||
|
return x, y
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _random_control_point(start: tuple, end: tuple) -> tuple:
|
||||||
|
"""
|
||||||
|
Ponto de controle aleatório deslocado perpendicularmente
|
||||||
|
à linha start→end (entre 10 % e 30 % do comprimento).
|
||||||
|
"""
|
||||||
|
mx = (start[0] + end[0]) / 2
|
||||||
|
my = (start[1] + end[1]) / 2
|
||||||
|
dist = math.hypot(end[0] - start[0], end[1] - start[1]) or 1
|
||||||
|
perp_x = -(end[1] - start[1]) / dist
|
||||||
|
perp_y = (end[0] - start[0]) / dist
|
||||||
|
offset = random.uniform(0.10, 0.30) * dist * random.choice([-1, 1])
|
||||||
|
return mx + perp_x * offset, my + perp_y * offset
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# API pública
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def move_to(self, x: float, y: float, steps: int = 0):
|
||||||
|
"""
|
||||||
|
Move o mouse da posição atual até (x, y) em trajetória curva.
|
||||||
|
steps=0 → calculado automaticamente pela distância.
|
||||||
|
"""
|
||||||
|
start = (self._x, self._y)
|
||||||
|
end = (x + random.uniform(-2, 2), y + random.uniform(-2, 2))
|
||||||
|
ctrl = self._random_control_point(start, end)
|
||||||
|
|
||||||
|
dist = math.hypot(end[0] - start[0], end[1] - start[1])
|
||||||
|
n = steps or max(8, int(dist / 12))
|
||||||
|
|
||||||
|
for i in range(1, n + 1):
|
||||||
|
t_raw = i / n
|
||||||
|
t = self._ease_in_out(t_raw)
|
||||||
|
px, py = self._bezier(t, start, ctrl, end)
|
||||||
|
|
||||||
|
# Jitter suave (microtremor)
|
||||||
|
jitter_scale = max(0.5, 2.5 * math.sin(math.pi * t_raw))
|
||||||
|
px += random.gauss(0, jitter_scale)
|
||||||
|
py += random.gauss(0, jitter_scale)
|
||||||
|
|
||||||
|
await self.page.mouse.move(px, py)
|
||||||
|
|
||||||
|
# Velocidade variável: mais devagar nas extremidades
|
||||||
|
speed_factor = 0.4 + 0.6 * math.sin(math.pi * t_raw)
|
||||||
|
await asyncio.sleep(random.uniform(0.005, 0.022) / speed_factor)
|
||||||
|
|
||||||
|
self._x, self._y = end
|
||||||
|
|
||||||
|
async def click(self, x: float, y: float, button: str = "left"):
|
||||||
|
"""Move até (x, y) e clica com pausa humana."""
|
||||||
|
await self.move_to(x, y)
|
||||||
|
await asyncio.sleep(random.uniform(0.05, 0.18)) # pausa pré-clique
|
||||||
|
await self.page.mouse.down(button=button)
|
||||||
|
await asyncio.sleep(random.uniform(0.04, 0.12)) # duração do clique
|
||||||
|
await self.page.mouse.up(button=button)
|
||||||
|
await asyncio.sleep(random.uniform(0.08, 0.25)) # pausa pós-clique
|
||||||
|
|
||||||
|
async def click_element(self, locator, offset_x: float = 0, offset_y: float = 0):
|
||||||
|
"""
|
||||||
|
Obtém o bounding box de um locator e clica no centro (com desvio opcional),
|
||||||
|
usando trajetória humana de mouse.
|
||||||
|
Faz scroll automático para o elemento ficar visível antes de clicar.
|
||||||
|
"""
|
||||||
|
await locator.scroll_into_view_if_needed()
|
||||||
|
box = await locator.bounding_box()
|
||||||
|
if box is None:
|
||||||
|
raise RuntimeError(f"Elemento sem bounding box visível: {locator}")
|
||||||
|
|
||||||
|
# Clica numa área levemente aleatória dentro do elemento
|
||||||
|
cx = box["x"] + box["width"] / 2 + offset_x + random.uniform(-3, 3)
|
||||||
|
cy = box["y"] + box["height"] / 2 + offset_y + random.uniform(-2, 2)
|
||||||
|
await self.click(cx, cy)
|
||||||
|
|
||||||
|
async def human_type(self, locator, text: str, clear_first: bool = True):
|
||||||
|
"""
|
||||||
|
Digita texto caractere a caractere com delay humano variável.
|
||||||
|
Inclui ocasionais micro-pausas como se a pessoa estivesse pensando.
|
||||||
|
"""
|
||||||
|
if clear_first:
|
||||||
|
await locator.click()
|
||||||
|
await asyncio.sleep(random.uniform(0.1, 0.2))
|
||||||
|
await self.page.keyboard.press("Control+a")
|
||||||
|
await asyncio.sleep(random.uniform(0.05, 0.1))
|
||||||
|
await self.page.keyboard.press("Delete")
|
||||||
|
await asyncio.sleep(random.uniform(0.05, 0.15))
|
||||||
|
|
||||||
|
for i, char in enumerate(text):
|
||||||
|
await locator.type(char, delay=0)
|
||||||
|
# Delay entre teclas: mais rápido no meio das palavras
|
||||||
|
if char == " ":
|
||||||
|
await asyncio.sleep(random.uniform(0.08, 0.18))
|
||||||
|
elif i > 0 and random.random() < 0.04:
|
||||||
|
# 4 % de chance de pausa longa (distração)
|
||||||
|
await asyncio.sleep(random.uniform(0.3, 0.7))
|
||||||
|
else:
|
||||||
|
await asyncio.sleep(random.uniform(0.04, 0.13))
|
||||||
|
|
||||||
|
async def idle_wiggle(self, duration_ms: int = 500):
|
||||||
|
"""Mexe o mouse levemente durante uma espera (simula impaciência)."""
|
||||||
|
end_time = asyncio.get_event_loop().time() + duration_ms / 1000
|
||||||
|
while asyncio.get_event_loop().time() < end_time:
|
||||||
|
dx = random.uniform(-8, 8)
|
||||||
|
dy = random.uniform(-5, 5)
|
||||||
|
await self.move_to(self._x + dx, self._y + dy, steps=4)
|
||||||
|
await asyncio.sleep(random.uniform(0.08, 0.20))
|
||||||
|
|
||||||
|
|
||||||
|
async def human_delay(min_ms: int = 300, max_ms: int = 900):
|
||||||
|
"""Pausa aleatória entre ações (em milissegundos)."""
|
||||||
|
await asyncio.sleep(random.uniform(min_ms, max_ms) / 1000)
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
# AUTOMAÇÃO SIGA
|
# AUTOMAÇÃO SIGA
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
class SigaAutomation:
|
class SigaAutomation:
|
||||||
"""Automação do sistema SIGA via Playwright."""
|
"""Automação do sistema SIGA via Playwright com comportamento humano."""
|
||||||
|
|
||||||
TIMEOUT = 30_000
|
TIMEOUT = 30_000
|
||||||
AUTH_TIMEOUT = 3_600_000 # 1 hora
|
AUTH_TIMEOUT = 3_600_000 # 1 hora
|
||||||
@@ -234,22 +377,39 @@ class SigaAutomation:
|
|||||||
self.playwright = None
|
self.playwright = None
|
||||||
self.context = None
|
self.context = None
|
||||||
self.page: Optional[Page] = None
|
self.page: Optional[Page] = None
|
||||||
|
self.mouse: Optional[HumanMouse] = None
|
||||||
|
|
||||||
async def launch(self):
|
async def launch(self):
|
||||||
self.playwright = await async_playwright().start()
|
self.playwright = await async_playwright().start()
|
||||||
|
|
||||||
# Define o caminho do perfil apontando para ./perfil_chromium na raiz do projeto
|
|
||||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||||
user_data_dir = os.path.join(project_root, "perfil_chromium")
|
user_data_dir = os.path.join(project_root, "perfil_chromium")
|
||||||
|
|
||||||
self.context = await self.playwright.chromium.launch_persistent_context(
|
self.context = await self.playwright.chromium.launch_persistent_context(
|
||||||
user_data_dir=user_data_dir,
|
user_data_dir=user_data_dir,
|
||||||
headless=False
|
headless=False,
|
||||||
|
# Passa por checagens simples de user-agent
|
||||||
|
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"
|
||||||
|
),
|
||||||
|
# Remove a flag que identifica automação
|
||||||
|
args=["--disable-blink-features=AutomationControlled"],
|
||||||
|
ignore_default_args=["--enable-automation"],
|
||||||
|
viewport={"width": 1366, "height": 768},
|
||||||
|
locale="pt-BR",
|
||||||
|
timezone_id="America/Cuiaba",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 'launch_persistent_context' já cria uma página por padrão
|
|
||||||
self.page = self.context.pages[0] if self.context.pages else await self.context.new_page()
|
self.page = self.context.pages[0] if self.context.pages else await self.context.new_page()
|
||||||
self.page.set_default_timeout(self.TIMEOUT)
|
self.page.set_default_timeout(self.TIMEOUT)
|
||||||
|
self.mouse = HumanMouse(self.page)
|
||||||
|
|
||||||
|
# Remove propriedade webdriver do navigator
|
||||||
|
await self.page.add_init_script(
|
||||||
|
"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
|
||||||
|
)
|
||||||
|
|
||||||
logger.info(f"🌐 Navegador iniciado com perfil: {user_data_dir}")
|
logger.info(f"🌐 Navegador iniciado com perfil: {user_data_dir}")
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
@@ -265,7 +425,6 @@ class SigaAutomation:
|
|||||||
page = self.page
|
page = self.page
|
||||||
await page.goto(Config.SIGA_URL)
|
await page.goto(Config.SIGA_URL)
|
||||||
logger.info("⏳ Aguardando login manual + reCAPTCHA...")
|
logger.info("⏳ Aguardando login manual + reCAPTCHA...")
|
||||||
logger.info(" → Faça login no navegador e resolva o captcha.")
|
|
||||||
|
|
||||||
await page.locator(
|
await page.locator(
|
||||||
"a:has-text('PRIMAVERA DO LESTE DL -'), "
|
"a:has-text('PRIMAVERA DO LESTE DL -'), "
|
||||||
@@ -273,9 +432,9 @@ class SigaAutomation:
|
|||||||
).first.wait_for(state="visible", timeout=self.AUTH_TIMEOUT)
|
).first.wait_for(state="visible", timeout=self.AUTH_TIMEOUT)
|
||||||
|
|
||||||
logger.info("✅ Login detectado!")
|
logger.info("✅ Login detectado!")
|
||||||
|
await human_delay(800, 1500)
|
||||||
|
|
||||||
async def check_session(self):
|
async def check_session(self):
|
||||||
"""Se sessão expirou, aguarda re-login e re-navega."""
|
|
||||||
try:
|
try:
|
||||||
login_field = self.page.get_by_role("textbox", name="Email/Usuário:")
|
login_field = self.page.get_by_role("textbox", name="Email/Usuário:")
|
||||||
if await login_field.is_visible(timeout=2000):
|
if await login_field.is_visible(timeout=2000):
|
||||||
@@ -290,45 +449,40 @@ class SigaAutomation:
|
|||||||
|
|
||||||
async def navigate_to_fundo_biblico(self):
|
async def navigate_to_fundo_biblico(self):
|
||||||
page = self.page
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Clicar no menu principal de localidade no topo
|
locality_dropdown = page.locator(
|
||||||
locality_dropdown = page.locator('//*[@id="navbar-container"]/div[2]/ul/li[3]/a')
|
'//*[@id="navbar-container"]/div[2]/ul/li[3]/a'
|
||||||
|
)
|
||||||
if await locality_dropdown.is_visible(timeout=5000):
|
if await locality_dropdown.is_visible(timeout=5000):
|
||||||
await locality_dropdown.click()
|
await mouse.click_element(locality_dropdown)
|
||||||
await page.wait_for_timeout(1000)
|
await human_delay(600, 1200)
|
||||||
|
|
||||||
# 2. Hover em "Localidades"
|
localidades_menu = page.locator(
|
||||||
localidades_menu = page.locator('//*[@id="navbar-container"]/div[2]/ul/li[3]/ul/li[2]/a')
|
'//*[@id="navbar-container"]/div[2]/ul/li[3]/ul/li[2]/a'
|
||||||
await localidades_menu.hover()
|
)
|
||||||
await page.wait_for_timeout(500)
|
await mouse.click_element(localidades_menu)
|
||||||
try:
|
await human_delay(400, 800)
|
||||||
await localidades_menu.click(timeout=2000)
|
|
||||||
except Exception:
|
|
||||||
pass # Se o clique falhar por sobreposição, o hover deve ser suficiente
|
|
||||||
await page.wait_for_timeout(1000)
|
|
||||||
|
|
||||||
# 3. Clicar na localidade alvo (BR 09-0231 - PRIMAVERA DO LESTE - CENTRO)
|
|
||||||
target_locality = page.locator('//*[@id="5044"]/a')
|
target_locality = page.locator('//*[@id="5044"]/a')
|
||||||
# O click tradicional falha em menus ocultos. O evento no JS contorna as validações visuais:
|
|
||||||
if await target_locality.count() > 0:
|
if await target_locality.count() > 0:
|
||||||
await target_locality.first.evaluate("el => el.click()")
|
await target_locality.first.evaluate("el => el.click()")
|
||||||
else:
|
else:
|
||||||
logger.warning("ID 5044 não visível de primeira, tentando via fallback de texto.")
|
|
||||||
fallback = page.locator(f'a:has-text("{Config.SIGA_DEST_CODE}")').last
|
fallback = page.locator(f'a:has-text("{Config.SIGA_DEST_CODE}")').last
|
||||||
if await fallback.count() > 0:
|
if await fallback.count() > 0:
|
||||||
await fallback.evaluate("el => el.click()")
|
await fallback.evaluate("el => el.click()")
|
||||||
|
|
||||||
await page.wait_for_timeout(3500) # Mais tempo para o SIGA recarregar a sessão
|
# Wiggle enquanto o SIGA recarrega
|
||||||
|
await mouse.idle_wiggle(3500)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"⚠️ Erro ao tentar mudar localidade: {e}")
|
logger.warning(f"⚠️ Erro ao tentar mudar localidade: {e}")
|
||||||
|
|
||||||
# 4. Encontrar o link Fundo Bíblico - Busca mais flexível (ignora espaços exatos)
|
|
||||||
fundo_link = page.get_by_role("link", name="Fundo Bíblico", exact=False).first
|
fundo_link = page.get_by_role("link", name="Fundo Bíblico", exact=False).first
|
||||||
# Esperamos apenas 'attached' (existir no DOM) em vez de 'visible', pois pode estar oculto num accordion
|
|
||||||
await fundo_link.wait_for(state="attached", timeout=15000)
|
await fundo_link.wait_for(state="attached", timeout=15000)
|
||||||
await fundo_link.evaluate("el => el.click()")
|
await mouse.click_element(fundo_link)
|
||||||
await page.wait_for_timeout(2000)
|
await human_delay(1000, 2000)
|
||||||
logger.info("📂 Navegou para Fundo Bíblico.")
|
logger.info("📂 Navegou para Fundo Bíblico.")
|
||||||
|
|
||||||
async def validate_and_enter_month(self):
|
async def validate_and_enter_month(self):
|
||||||
@@ -339,8 +493,8 @@ class SigaAutomation:
|
|||||||
month_link = page.get_by_role("link", name=month_text)
|
month_link = page.get_by_role("link", name=month_text)
|
||||||
try:
|
try:
|
||||||
await month_link.wait_for(state="visible", timeout=10000)
|
await month_link.wait_for(state="visible", timeout=10000)
|
||||||
await month_link.click()
|
await self.mouse.click_element(month_link)
|
||||||
await page.wait_for_timeout(2000)
|
await human_delay(1000, 2000)
|
||||||
logger.info(f"📅 Entrou no {month_text}")
|
logger.info(f"📅 Entrou no {month_text}")
|
||||||
except PlaywrightTimeout:
|
except PlaywrightTimeout:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
@@ -351,8 +505,8 @@ class SigaAutomation:
|
|||||||
# ---------- LANÇAMENTO DE SAÍDA ----------
|
# ---------- LANÇAMENTO DE SAÍDA ----------
|
||||||
|
|
||||||
async def process_group(self, group: SaleGroup) -> List[int]:
|
async def process_group(self, group: SaleGroup) -> List[int]:
|
||||||
"""Cria uma SAÍDA para o grupo. Retorna IDs lançados com sucesso."""
|
|
||||||
page = self.page
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
products = group.get_aggregated_products()
|
products = group.get_aggregated_products()
|
||||||
|
|
||||||
logger.info(f"\n{'='*60}")
|
logger.info(f"\n{'='*60}")
|
||||||
@@ -362,22 +516,24 @@ class SigaAutomation:
|
|||||||
await self.check_session()
|
await self.check_session()
|
||||||
|
|
||||||
# 1. Novo → Saída
|
# 1. Novo → Saída
|
||||||
await page.get_by_role("button", name=" Novo ").click()
|
novo_btn = page.get_by_role("button", name=" Novo ")
|
||||||
await page.wait_for_timeout(1000)
|
await mouse.click_element(novo_btn)
|
||||||
await page.get_by_role("link", name="Saída").click()
|
await human_delay(700, 1300)
|
||||||
await page.wait_for_timeout(1500)
|
|
||||||
|
|
||||||
# 2. Datepicker (aparece automaticamente após clicar "Saída")
|
saida_link = page.get_by_role("link", name="Saída")
|
||||||
await self._select_date(group.data_venda.day)
|
await mouse.click_element(saida_link)
|
||||||
|
await human_delay(1000, 1800)
|
||||||
|
|
||||||
# Aguardar loading do sistema (spinner "Aguarde...") após seleção de data
|
# 2. Datepicker
|
||||||
# O destinatário é preenchido automaticamente após a data
|
await self._select_date(group.data_venda)
|
||||||
await page.wait_for_timeout(2000)
|
|
||||||
|
# Aguardar spinner
|
||||||
|
await human_delay(500, 1000)
|
||||||
try:
|
try:
|
||||||
await page.locator("text=Aguarde...").wait_for(state="hidden", timeout=10000)
|
await page.locator("text=Aguarde...").wait_for(state="hidden", timeout=10000)
|
||||||
except PlaywrightTimeout:
|
except PlaywrightTimeout:
|
||||||
pass
|
pass
|
||||||
await page.wait_for_timeout(1000)
|
await human_delay(800, 1500)
|
||||||
|
|
||||||
# 3. Inserir produtos
|
# 3. Inserir produtos
|
||||||
successful_ids: List[int] = []
|
successful_ids: List[int] = []
|
||||||
@@ -390,79 +546,115 @@ class SigaAutomation:
|
|||||||
else:
|
else:
|
||||||
failed_products.append(product)
|
failed_products.append(product)
|
||||||
|
|
||||||
# 4. Se todos falharam → cancelar
|
|
||||||
if not successful_ids:
|
if not successful_ids:
|
||||||
logger.error("❌ Todos produtos falharam! Cancelando SAÍDA...")
|
logger.error("❌ Todos produtos falharam! Cancelando SAÍDA...")
|
||||||
await self._cancel_saida()
|
await self._cancel_saida()
|
||||||
return []
|
return []
|
||||||
|
|
||||||
if failed_products:
|
if failed_products:
|
||||||
codes = [p.code for p in failed_products]
|
logger.warning(f"⚠️ Produtos não encontrados: {[p.code for p in failed_products]}")
|
||||||
logger.warning(f"⚠️ Produtos não encontrados: {codes}")
|
|
||||||
|
|
||||||
# 5. Ler valor calculado e preencher campo de pagamento
|
# 4. Pagamento
|
||||||
await self._fill_payment_value(group.meio_pag)
|
await self._fill_payment_value(group.meio_pag)
|
||||||
|
|
||||||
# 6. Confirmar
|
# 5. Confirmar
|
||||||
await self._confirm()
|
await self._confirm()
|
||||||
logger.info(f"✅ SAÍDA confirmada! IDs: {successful_ids}")
|
logger.info(f"✅ SAÍDA confirmada! IDs: {successful_ids}")
|
||||||
return successful_ids
|
return successful_ids
|
||||||
|
|
||||||
# ---------- AÇÕES INTERNAS ----------
|
# ---------- DATEPICKER ----------
|
||||||
|
|
||||||
async def _select_date(self, day: int):
|
async def _select_date(self, target: date):
|
||||||
"""Seleciona o dia no datepicker Bootstrap (aparece automaticamente)."""
|
"""
|
||||||
|
Aguarda o datepicker Bootstrap abrir e clica no dia desejado.
|
||||||
|
O mês exibido é sempre o mês de trabalho do SIGA — sem navegação.
|
||||||
|
Dias de meses adjacentes têm classe 'old' ou 'new' e são ignorados.
|
||||||
|
"""
|
||||||
page = self.page
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
try:
|
# Aguarda o datepicker aparecer (o SIGA abre automaticamente)
|
||||||
dp = page.locator(".datepicker-days")
|
dp = page.locator(".datepicker-days")
|
||||||
await dp.wait_for(state="visible", timeout=5000)
|
try:
|
||||||
|
await dp.wait_for(state="visible", timeout=5_000)
|
||||||
cells = dp.locator("td.day:not(.old):not(.new)")
|
except PlaywrightTimeout:
|
||||||
count = await cells.count()
|
# Fallback: tenta abrir clicando em algum input de data visível
|
||||||
for i in range(count):
|
logger.warning("⚠️ Datepicker não abriu automaticamente, tentando campo...")
|
||||||
text = (await cells.nth(i).inner_text()).strip()
|
input_data = page.locator(
|
||||||
if text == str(day):
|
"input.datepicker, input[name*='data'], input[id*='data']"
|
||||||
await cells.nth(i).click()
|
).first
|
||||||
logger.info(f"📅 Dia {day} selecionado.")
|
try:
|
||||||
|
await mouse.click_element(input_data)
|
||||||
|
await human_delay(400, 700)
|
||||||
|
await dp.wait_for(state="visible", timeout=5_000)
|
||||||
|
except PlaywrightTimeout:
|
||||||
|
logger.warning("⚠️ Datepicker não encontrado, continuando sem selecionar data.")
|
||||||
return
|
return
|
||||||
|
|
||||||
raise RuntimeError(f"Dia {day} não encontrado no datepicker!")
|
# Aproxima o mouse do calendário antes de interagir (comportamento humano)
|
||||||
except PlaywrightTimeout:
|
dp_box = await dp.bounding_box()
|
||||||
logger.warning("⚠️ Datepicker não apareceu, continuando...")
|
if dp_box:
|
||||||
|
await mouse.move_to(
|
||||||
|
dp_box["x"] + dp_box["width"] / 2,
|
||||||
|
dp_box["y"] - 20,
|
||||||
|
)
|
||||||
|
await human_delay(150, 350)
|
||||||
|
|
||||||
|
# Localiza todas as células do mês atual (sem .old e sem .new)
|
||||||
|
cells = dp.locator("td.day:not(.old):not(.new)")
|
||||||
|
count = await cells.count()
|
||||||
|
|
||||||
|
for i in range(count):
|
||||||
|
cell = cells.nth(i)
|
||||||
|
if (await cell.inner_text()).strip() == str(target.day):
|
||||||
|
await mouse.click_element(cell)
|
||||||
|
logger.info(f"📅 Data selecionada: {target.strftime('%d/%m/%Y')}")
|
||||||
|
return
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Dia {target.day} não encontrado no datepicker "
|
||||||
|
f"({target.month:02d}/{target.year})."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- AÇÕES INTERNAS ----------
|
||||||
|
|
||||||
async def _add_product(self, code: str, qty: int) -> bool:
|
async def _add_product(self, code: str, qty: int) -> bool:
|
||||||
"""Insere um produto na SAÍDA. Retorna True se OK."""
|
|
||||||
page = self.page
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
try:
|
try:
|
||||||
# Abrir dropdown
|
# Abrir dropdown
|
||||||
await page.get_by_role("link", name="* Selecione * ").click()
|
select_btn = page.get_by_role("link", name="* Selecione * ")
|
||||||
await page.wait_for_timeout(500)
|
await mouse.click_element(select_btn)
|
||||||
|
await human_delay(400, 700)
|
||||||
|
|
||||||
# Buscar produto
|
# Buscar produto
|
||||||
search = page.get_by_label("", exact=True)
|
search = page.get_by_label("", exact=True)
|
||||||
await search.fill(code)
|
await mouse.click_element(search)
|
||||||
await search.press("Enter")
|
await human_delay(150, 300)
|
||||||
await page.wait_for_timeout(2000)
|
await mouse.human_type(search, code, clear_first=False)
|
||||||
|
await asyncio.sleep(random.uniform(0.3, 0.6))
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
await human_delay(1200, 2000)
|
||||||
|
|
||||||
# Selecionar produto exato
|
# Selecionar produto
|
||||||
selected = await self._select_exact_product(code)
|
selected = await self._select_exact_product(code)
|
||||||
if not selected:
|
if not selected:
|
||||||
logger.warning(f" ❌ Produto '{code}' não encontrado no catálogo.")
|
logger.warning(f" ❌ Produto '{code}' não encontrado no catálogo.")
|
||||||
await page.keyboard.press("Escape")
|
await page.keyboard.press("Escape")
|
||||||
await page.wait_for_timeout(500)
|
await human_delay(300, 600)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
await page.wait_for_timeout(500)
|
await human_delay(400, 700)
|
||||||
|
|
||||||
# Preencher quantidade
|
# Quantidade
|
||||||
qty_field = page.locator("#f_quantidade")
|
qty_field = page.locator("#f_quantidade")
|
||||||
await qty_field.click()
|
await mouse.click_element(qty_field)
|
||||||
await qty_field.fill(str(qty))
|
await mouse.human_type(qty_field, str(qty))
|
||||||
|
|
||||||
# Inserir
|
# Inserir
|
||||||
await page.locator("#btn-inserir-produto").click()
|
inserir_btn = page.locator("#btn-inserir-produto")
|
||||||
await page.wait_for_timeout(1500)
|
await mouse.click_element(inserir_btn)
|
||||||
|
await human_delay(1000, 1800)
|
||||||
|
|
||||||
logger.info(f" ✅ {code} x{qty} inserido.")
|
logger.info(f" ✅ {code} x{qty} inserido.")
|
||||||
return True
|
return True
|
||||||
@@ -476,27 +668,28 @@ class SigaAutomation:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
async def _select_exact_product(self, code: str) -> bool:
|
async def _select_exact_product(self, code: str) -> bool:
|
||||||
"""Tenta selecionar o produto exato no dropdown select2."""
|
|
||||||
page = self.page
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
code_upper = code.strip().upper()
|
code_upper = code.strip().upper()
|
||||||
|
|
||||||
# Estratégia 1: texto exato
|
# Estratégia 1: texto exato
|
||||||
try:
|
try:
|
||||||
exact = page.locator("#select2-drop").get_by_text(code, exact=True)
|
exact = page.locator("#select2-drop").get_by_text(code, exact=True)
|
||||||
if await exact.count() > 0 and await exact.first.is_visible(timeout=2000):
|
if await exact.count() > 0 and await exact.first.is_visible(timeout=2000):
|
||||||
await exact.first.click()
|
await mouse.click_element(exact.first)
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Estratégia 2: opção que começa com o código
|
# Estratégia 2: texto que começa com o código
|
||||||
try:
|
try:
|
||||||
results = page.locator("#select2-drop .select2-results li")
|
results = page.locator("#select2-drop .select2-results li")
|
||||||
count = await results.count()
|
count = await results.count()
|
||||||
for i in range(count):
|
for i in range(count):
|
||||||
text = (await results.nth(i).inner_text()).strip().upper()
|
item = results.nth(i)
|
||||||
|
text = (await item.inner_text()).strip().upper()
|
||||||
if text.startswith(code_upper + " ") or text == code_upper:
|
if text.startswith(code_upper + " ") or text == code_upper:
|
||||||
await results.nth(i).click()
|
await mouse.click_element(item)
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@@ -506,9 +699,10 @@ class SigaAutomation:
|
|||||||
options = page.get_by_role("option")
|
options = page.get_by_role("option")
|
||||||
count = await options.count()
|
count = await options.count()
|
||||||
for i in range(count):
|
for i in range(count):
|
||||||
text = (await options.nth(i).inner_text()).strip().upper()
|
opt = options.nth(i)
|
||||||
|
text = (await opt.inner_text()).strip().upper()
|
||||||
if text.startswith(code_upper):
|
if text.startswith(code_upper):
|
||||||
await options.nth(i).click()
|
await mouse.click_element(opt)
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@@ -516,17 +710,18 @@ class SigaAutomation:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
async def _cancel_saida(self):
|
async def _cancel_saida(self):
|
||||||
page = self.page
|
cancel = self.page.locator(
|
||||||
cancel = page.locator('button.btn.btn-link.no-border[data-dismiss="modal"]', has_text="Cancelar")
|
'button.btn.btn-link.no-border[data-dismiss="modal"]',
|
||||||
await cancel.click()
|
has_text="Cancelar",
|
||||||
await page.wait_for_timeout(2000)
|
)
|
||||||
|
await self.mouse.click_element(cancel)
|
||||||
|
await human_delay(1000, 2000)
|
||||||
logger.info("🚫 SAÍDA cancelada.")
|
logger.info("🚫 SAÍDA cancelada.")
|
||||||
|
|
||||||
async def _fill_payment_value(self, meio_pag: str):
|
async def _fill_payment_value(self, meio_pag: str):
|
||||||
"""Lê o valor total dos produtos e preenche o campo correto (Dinheiro ou PIX)."""
|
|
||||||
page = self.page
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
# Ler o valor total dos produtos calculado pelo sistema
|
|
||||||
try:
|
try:
|
||||||
valor_produtos = await page.locator("#f_valorproduto").input_value()
|
valor_produtos = await page.locator("#f_valorproduto").input_value()
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -535,36 +730,44 @@ class SigaAutomation:
|
|||||||
if not valor_produtos or valor_produtos.strip() == "":
|
if not valor_produtos or valor_produtos.strip() == "":
|
||||||
valor_produtos = "0,00"
|
valor_produtos = "0,00"
|
||||||
|
|
||||||
|
# Pausa humana antes de preencher pagamento
|
||||||
|
await human_delay(400, 900)
|
||||||
|
|
||||||
if meio_pag == "DINHEIRO":
|
if meio_pag == "DINHEIRO":
|
||||||
field = page.locator("#f_valorcaixa")
|
field = page.locator("#f_valorcaixa")
|
||||||
await field.click()
|
await mouse.click_element(field)
|
||||||
await field.fill(valor_produtos)
|
await mouse.human_type(field, valor_produtos)
|
||||||
logger.info(f"💰 Valor em Dinheiro no Caixa: {valor_produtos}")
|
logger.info(f"💰 Dinheiro no Caixa: {valor_produtos}")
|
||||||
elif meio_pag == "PIX":
|
elif meio_pag == "PIX":
|
||||||
field = page.locator("#f_valorQrcodePix")
|
field = page.locator("#f_valorQrcodePix")
|
||||||
await field.click()
|
await mouse.click_element(field)
|
||||||
await field.fill(valor_produtos)
|
await mouse.human_type(field, valor_produtos)
|
||||||
logger.info(f"💰 Pagto QRCode/PIX: {valor_produtos}")
|
logger.info(f"💰 PIX/QRCode: {valor_produtos}")
|
||||||
else:
|
else:
|
||||||
field = page.locator("#f_valorcaixa")
|
field = page.locator("#f_valorcaixa")
|
||||||
await field.click()
|
await mouse.click_element(field)
|
||||||
await field.fill(valor_produtos)
|
await mouse.human_type(field, valor_produtos)
|
||||||
logger.info(f"💰 Valor (fallback dinheiro): {valor_produtos}")
|
logger.info(f"💰 Fallback dinheiro: {valor_produtos}")
|
||||||
|
|
||||||
async def _confirm(self):
|
async def _confirm(self):
|
||||||
page = self.page
|
page = self.page
|
||||||
await page.get_by_role("button", name=" Confirmar").click()
|
mouse = self.mouse
|
||||||
await page.wait_for_timeout(2000)
|
|
||||||
await page.get_by_role("button", name="Ok").click()
|
await human_delay(500, 1000)
|
||||||
await page.wait_for_timeout(2000)
|
confirmar = page.get_by_role("button", name=" Confirmar")
|
||||||
|
await mouse.click_element(confirmar)
|
||||||
|
await human_delay(1200, 2200)
|
||||||
|
|
||||||
|
ok_btn = page.get_by_role("button", name="Ok")
|
||||||
|
await ok_btn.wait_for(state="visible", timeout=10_000)
|
||||||
|
await mouse.click_element(ok_btn)
|
||||||
|
await human_delay(1000, 2000)
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
# APLICAÇÃO
|
# APLICAÇÃO
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
class Application:
|
class Application:
|
||||||
"""Orquestrador principal."""
|
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
Config.load()
|
Config.load()
|
||||||
|
|
||||||
@@ -577,17 +780,14 @@ class Application:
|
|||||||
logger.info(f"📅 Mês: {month:02d}/{year}")
|
logger.info(f"📅 Mês: {month:02d}/{year}")
|
||||||
logger.info(f"{'='*60}\n")
|
logger.info(f"{'='*60}\n")
|
||||||
|
|
||||||
# 1. Ler planilhas
|
|
||||||
sheets = GoogleSheetsService(Config.GOOGLE_CREDENTIALS_FILE, Config.SPREADSHEET_ID)
|
sheets = GoogleSheetsService(Config.GOOGLE_CREDENTIALS_FILE, Config.SPREADSHEET_ID)
|
||||||
vendas = sheets.read_vendas(month, year)
|
vendas = sheets.read_vendas(month, year)
|
||||||
launched_ids = sheets.read_lancamentos()
|
launched_ids = sheets.read_lancamentos()
|
||||||
|
|
||||||
# 2. Agrupar vendas pendentes
|
|
||||||
groups = group_sales(vendas, launched_ids)
|
groups = group_sales(vendas, launched_ids)
|
||||||
if not groups:
|
if not groups:
|
||||||
return
|
return
|
||||||
|
|
||||||
# 3. Automação SIGA
|
|
||||||
siga = SigaAutomation()
|
siga = SigaAutomation()
|
||||||
try:
|
try:
|
||||||
await siga.launch()
|
await siga.launch()
|
||||||
@@ -608,7 +808,6 @@ class Application:
|
|||||||
else:
|
else:
|
||||||
total_fail.extend(group.all_ids)
|
total_fail.extend(group.all_ids)
|
||||||
|
|
||||||
# Resumo
|
|
||||||
logger.info(f"\n{'='*60}")
|
logger.info(f"\n{'='*60}")
|
||||||
logger.info(f"📊 RESUMO FINAL")
|
logger.info(f"📊 RESUMO FINAL")
|
||||||
logger.info(f" ✅ Lançados: {len(total_ok)} vendas")
|
logger.info(f" ✅ Lançados: {len(total_ok)} vendas")
|
||||||
|
|||||||
20
test.html
Normal file
20
test.html
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<input type="text" class="datepicker1" id="dp1">
|
||||||
|
<input type="text" class="datepicker2" id="dp2">
|
||||||
|
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
|
||||||
|
<script>
|
||||||
|
$('.datepicker1').datepicker();
|
||||||
|
$('.datepicker2').datepicker();
|
||||||
|
// open the first one
|
||||||
|
$('.datepicker1').datepicker('show');
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
19
test2.html
Normal file
19
test2.html
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<input type="text" class="datepicker1">
|
||||||
|
<input type="text" class="datepicker2">
|
||||||
|
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
|
||||||
|
<script>
|
||||||
|
$('.datepicker1').datepicker();
|
||||||
|
$('.datepicker2').datepicker();
|
||||||
|
$('.datepicker2').datepicker('show'); // show the second one
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
59
test_datepicker.py
Normal file
59
test_datepicker.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import asyncio
|
||||||
|
from playwright.async_api import async_playwright
|
||||||
|
import os
|
||||||
|
|
||||||
|
html_content = """
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<input type="text" class="datepicker1" id="dp1">
|
||||||
|
<input type="text" class="datepicker2" id="dp2">
|
||||||
|
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
|
||||||
|
<script>
|
||||||
|
$('.datepicker1').datepicker();
|
||||||
|
$('.datepicker2').datepicker();
|
||||||
|
// open the first one
|
||||||
|
$('.datepicker1').datepicker('show');
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def test_date():
|
||||||
|
with open("test.html", "w") as f:
|
||||||
|
f.write(html_content)
|
||||||
|
|
||||||
|
async with async_playwright() as p:
|
||||||
|
browser = await p.chromium.launch(headless=True)
|
||||||
|
page = await browser.new_page()
|
||||||
|
await page.goto(f"file://{os.path.abspath('test.html')}")
|
||||||
|
|
||||||
|
day = 15
|
||||||
|
|
||||||
|
# Original logic
|
||||||
|
try:
|
||||||
|
dp = page.locator(".datepicker-days")
|
||||||
|
await dp.wait_for(state="visible", timeout=5000)
|
||||||
|
|
||||||
|
cells = dp.locator("td.day:not(.old):not(.new)")
|
||||||
|
count = await cells.count()
|
||||||
|
print(f"Total cells found: {count}")
|
||||||
|
for i in range(count):
|
||||||
|
text = (await cells.nth(i).inner_text()).strip()
|
||||||
|
if text == str(day):
|
||||||
|
print(f"Trying to click cell {i} with text {text}")
|
||||||
|
await cells.nth(i).click(timeout=1000)
|
||||||
|
print(f"📅 Dia {day} selecionado.")
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
print(f"ERROR: {type(e).__name__}: {str(e)}")
|
||||||
|
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(test_date())
|
||||||
44
test_datepicker2.py
Normal file
44
test_datepicker2.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import asyncio
|
||||||
|
from playwright.async_api import async_playwright
|
||||||
|
import os
|
||||||
|
|
||||||
|
html_content = '''
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<input type="text" class="datepicker1">
|
||||||
|
<input type="text" class="datepicker2">
|
||||||
|
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
|
||||||
|
<script>
|
||||||
|
$('.datepicker1').datepicker();
|
||||||
|
$('.datepicker2').datepicker();
|
||||||
|
$('.datepicker2').datepicker('show'); // show the second one
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
'''
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
with open('test2.html', 'w') as f:
|
||||||
|
f.write(html_content)
|
||||||
|
async with async_playwright() as p:
|
||||||
|
browser = await p.chromium.launch()
|
||||||
|
page = await browser.new_page()
|
||||||
|
await page.goto(f"file://{os.path.abspath('test2.html')}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
dp = page.locator('.datepicker-days')
|
||||||
|
await dp.wait_for(state='visible', timeout=3000)
|
||||||
|
print('WAIT FOR COM SUCESSO')
|
||||||
|
except Exception as e:
|
||||||
|
print(f'ERRO ESPERADO: {type(e).__name__} - {str(e)}')
|
||||||
|
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
asyncio.run(main())
|
||||||
Reference in New Issue
Block a user