domovoy_bot/scraper_gis/map_and_auth.py

75 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import os
import logging
from playwright.async_api import async_playwright
from sqlalchemy import create_engine
from models import Base
# Настройка логов
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("GIS-Mapper")
USER_DATA_DIR = "/app/browser_context"
TARGET_URL = "https://dom.gosuslugi.ru/"
async def send_tg_report(message):
token = os.getenv("TELEGRAM_BOT_TOKEN")
chat_id = os.getenv("TELEGRAM_CHAT_ID")
if not token or not chat_id: return
import aiohttp
url = f"https://api.telegram.org/bot{token}/sendMessage"
async with aiohttp.ClientSession() as session:
await session.post(url, json={"chat_id": chat_id, "text": message, "parse_mode": "HTML"})
async def map_personal_account():
async with async_playwright() as p:
logger.info("Starting browser with persistent context...")
context = await p.chromium.launch_persistent_context(
user_data_dir=USER_DATA_DIR,
headless=False, # Обязательно False, чтобы ты видел окно!
args=["--no-sandbox", "--disable-setuid-sandbox"]
)
page = await context.new_page()
await page.goto(TARGET_URL)
logger.info("Waiting for user to log in...")
await send_tg_report("🌐 <b>Браузер запущен!</b>\n\nЗаходи по ссылке: http://192.168.10.116:6080/vnc.html\nЛогинься в ГИС ЖКХ. Я жду появления личного кабинета...")
# Ждем появления элемента, который есть только в личном кабинете
# Например, кнопка "Выйти" или имя пользователя
try:
# Ждем долго (10 минут), пока ты вводишь пароли и СМС
await page.wait_for_selector("text=Выйти", timeout=600000)
logger.info("User logged in successfully!")
await send_tg_report("✅ <b>Успешный вход!</b>\n\nЯ вижу личный кабинет. Начинаю сканирование структуры разделов...")
# Снимаем главный экран ЛК
await page.screenshot(path="/app/screenshots/dashboard.png", full_page=True)
# Собираем ссылки из главного меню
menu_items = await page.query_selector_all("a")
structure = []
for item in menu_items:
text = await item.inner_text()
href = await item.get_attribute("href")
if text and href and href.startswith("/"):
structure.append(f"- **{text.strip()}**: `{href}`")
# Сохраняем карту в Обсидиан (через маунт)
report_path = "/app/downloads/nas/GIS_STRUCTURE_MAP.md"
with open(report_path, "w") as f:
f.write("# 🗺️ Карта Личного Кабинета ГИС ЖКХ\n\n")
f.write(f"Дата сканирования: {asyncio.get_event_loop().time()}\n\n")
f.write("\n".join(set(structure)))
await send_tg_report(f"🗺️ <b>Карта ЛК составлена!</b>\n\nНайдено разделов: {len(set(structure))}\nФайл сохранен в Obsidian.")
except Exception as e:
logger.error(f"Error during mapping: {e}")
await send_tg_report(f"❌ <b>Ошибка при сканировании ЛК:</b>\n<code>{str(e)}</code>")
await context.close()
if __name__ == "__main__":
asyncio.run(map_personal_account())