"""Адаптеры источников: один вход, много форматов. detect() смотрит на url и тело ответа, parse() вытаскивает записи. Каждый адаптер обязан вернуть список RawItem и не падать на мусоре. """ import json, re from dataclasses import dataclass from typing import List from urllib.parse import urljoin, urlparse from bs4 import BeautifulSoup from lxml import etree BAD_TEXT = re.compile( r"^(вход|регистрация|логин|войти|наверх|домой|главная|правила|контакты|поиск|меню|" r"login|sign ?up|register|home|search|contact|privacy|terms|about|next|prev|page \d+)$", re.I) BAD_URL = re.compile(r"(/login|/register|/search|/terms|/privacy|/contact|javascript:|mailto:|#)", re.I) @dataclass class RawItem: title: str url: str ts: str = "" snippet: str = "" extra: dict = None def _clean(t: str) -> str: return re.sub(r"\s+", " ", (t or "")).strip() def detect(url: str, text: str, headers: dict | None = None) -> str: low = url.lower() head = (text or "")[:600].lstrip() ctype = (headers or {}).get("content-type", "").lower() if "t.me/s/" in low: return "tgweb" if low.endswith((".json", ".jsonl")) or low.split("?")[0].endswith("/latest.json") or head.startswith(("{", "[")): return "json" if head.startswith(" 4: return None if isinstance(obj, dict): for k in LIST_KEYS: v = obj.get(k) if isinstance(v, list) and v and isinstance(v[0], (dict, str)): return v for v in obj.values(): if isinstance(v, (dict, list)): r = _walk_lists(v, depth + 1) if r: return r if isinstance(obj, list) and obj and isinstance(obj[0], (dict, str)): return obj return None def parse_json(url: str, text: str) -> List[RawItem]: try: data = json.loads(text) except Exception: # jsonl / обрезанный json out = [] for line in text.splitlines(): line = line.strip().rstrip(",") if line.startswith("{") and line.endswith("}"): try: out.append(json.loads(line)) except Exception: pass data = out or {} rows = _walk_lists(data) or [] base = f"{urlparse(url).scheme}://{urlparse(url).netloc}" items, seen = [], set() for r in rows[:400]: if isinstance(r, str): t, u, ts, sn = r, url, "", "" else: t = _clean(_first(r, TITLE_KEYS)) u = _first(r, URL_KEYS) ts = _first(r, TS_KEYS) sn = _clean(_first(r, BODY_KEYS))[:400] if not t: continue if not u: u = url u = urljoin(base + "/", u) if u in seen: continue seen.add(u) items.append(RawItem(t[:300], u, ts, sn, {"fmt": "json"})) return items # ---------- RSS / Atom ---------- def parse_rss(url: str, text: str) -> List[RawItem]: try: root = etree.fromstring(text.encode("utf-8", "ignore"), parser=etree.XMLParser(recover=True, huge_tree=True)) except Exception: return [] out = [] for node in root.iter(): tag = etree.QName(node).localname.lower() if tag not in ("item", "entry"): continue d = {} for ch in node: ct = etree.QName(ch).localname.lower() if ct == "link": d["link"] = ch.get("href") or (ch.text or "") elif ct in ("title", "pubdate", "updated", "published", "description", "summary", "content"): d[ct] = (ch.text or "") if ct not in ("description", "content") else "".join(ch.itertext()) t = _clean(d.get("title", "")) u = _clean(d.get("link", "")) if t and u: out.append(RawItem(t[:300], u, d.get("pubdate") or d.get("updated") or d.get("published") or "", _clean(d.get("description") or d.get("summary") or "")[:400], {"fmt": "rss"})) return out[:400] # ---------- XenForo ---------- def parse_xenforo(url: str, text: str) -> List[RawItem]: soup = BeautifulSoup(text, "lxml") base = f"{urlparse(url).scheme}://{urlparse(url).netloc}" items, seen = [], set() nodes = soup.select("div.structItem-title a, h3.node-title a, .structItem-title a") if not nodes: nodes = soup.select("a[href*='/threads/'], a[href*='/topic/']") for a in nodes: t = _clean(a.get_text(" ")) href = a.get("href") or "" if not t or not href or BAD_URL.search(href): continue u = urljoin(base + "/", href) if u in seen: continue seen.add(u) parent = a.find_parent("div", class_="structItem") or a.find_parent("li") ts = "" if parent: tm = parent.find("time") if tm: ts = tm.get("datetime") or tm.get_text(" ") items.append(RawItem(t[:300], u, _clean(ts), "", {"fmt": "xenforo"})) return items[:300] # ---------- Telegram web ---------- def parse_tgweb(url: str, text: str) -> List[RawItem]: soup = BeautifulSoup(text, "lxml") chan = url.rstrip("/").split("/s/")[-1].split("/")[0] items = [] for box in soup.select("div.tgme_widget_message"): body = box.select_one("div.tgme_widget_message_text") if not body: continue t = _clean(body.get_text(" ")) if len(t) < 20: continue data_post = box.get("data-post") or "" ts = "" tm = box.select_one("time") if tm: ts = tm.get("datetime") or "" items.append(RawItem(t[:300], f"https://t.me/{data_post}" if data_post else url, ts, t[:400], {"fmt": "tgweb", "chan": chan})) return items[:200] # ---------- generic HTML ---------- def parse_html(url: str, text: str) -> List[RawItem]: soup = BeautifulSoup(text, "lxml") for bad in soup(["script", "style", "nav", "header", "footer", "form"]): bad.decompose() base = f"{urlparse(url).scheme}://{urlparse(url).netloc}" root = soup.select_one("main, article, div#content, div.content, div.container") or soup items, seen = [], set() for a in root.find_all("a", href=True): t = _clean(a.get_text(" ")) href = a["href"] if len(t) < 12 or len(t) > 300: continue if BAD_TEXT.match(t) or BAD_URL.search(href): continue u = urljoin(base + "/", href) if urlparse(u).netloc != urlparse(url).netloc or u in seen: continue seen.add(u) items.append(RawItem(t, u, "", "", {"fmt": "html"})) return items[:250] # ---------- pastebin archive ---------- PASTE_ID = re.compile(r'href="/([A-Za-z0-9]{8})"[^>]*>([^<]{0,120})') def parse_pastebin(url: str, text: str) -> List[RawItem]: out, seen = [], set() for pid, title in PASTE_ID.findall(text): if pid in seen or pid in ("archive", "login", "signup", "trends", "pro"): continue seen.add(pid) t = _clean(title) or f"paste {pid}" out.append(RawItem(t[:300], f"https://pastebin.com/{pid}", "", "", {"fmt": "pastebin"})) return out[:200] PARSERS = {"json": parse_json, "rss": parse_rss, "xenforo": parse_xenforo, "tgweb": parse_tgweb, "html": parse_html, "pastebin": parse_pastebin} def parse(url: str, text: str, headers: dict | None = None, adapter: str | None = None) -> List[RawItem]: if adapter and adapter in PARSERS: return PARSERS[adapter](url, text) kind = detect(url, text, headers) return PARSERS.get(kind, parse_html)(url, text)