#!/usr/bin/env python3 """Проверка Open Graph и Twitter Card.""" from __future__ import annotations import argparse import json from pathlib import Path from urllib.parse import urljoin import requests from bs4 import BeautifulSoup REQUIRED = ("og:title", "og:description", "og:image", "og:url", "og:type") def meta(soup: BeautifulSoup, key: str) -> str: tag = soup.find("meta", attrs={"property": key}) if tag is None: tag = soup.find("meta", attrs={"name": key}) return (tag.get("content") or "").strip() if tag else "" def main() -> int: parser = argparse.ArgumentParser(description="Проверить Open Graph") parser.add_argument("url", nargs="?", default="https://example.com/") parser.add_argument("--timeout", type=float, default=15.0) parser.add_argument("--skip-image-check", action="store_true") parser.add_argument("--json", type=Path, help="Сохранить отчёт") args = parser.parse_args() session = requests.Session() session.headers["User-Agent"] = "popovdev-scriptdock/1.0" try: response = session.get(args.url, timeout=args.timeout) response.raise_for_status() except requests.RequestException as error: print(f"Не удалось загрузить страницу: {error}") return 2 soup = BeautifulSoup(response.content, "html.parser") values = {key: meta(soup, key) for key in REQUIRED} twitter_card = meta(soup, "twitter:card") image = values["og:image"] image_status = None image_type = "" problems = [] for key in REQUIRED: if not values[key]: problems.append(f"нет {key}") if values["og:title"] and len(values["og:title"]) > 70: problems.append("og:title длиннее 70 символов") if values["og:description"] and len(values["og:description"]) > 200: problems.append("og:description длиннее 200 символов") if image: absolute = urljoin(response.url, image) parts = absolute.split("://", 1) if len(parts) != 2: problems.append("og:image не абсолютный") elif not args.skip_image_check: try: check = session.head(absolute, timeout=args.timeout, allow_redirects=True) image_status = check.status_code image_type = check.headers.get("Content-Type", "") if image_status >= 400: problems.append(f"og:image отвечает {image_status}") elif image_type and not image_type.startswith("image/"): problems.append(f"og:image отдаёт {image_type}") except requests.RequestException as error: problems.append(f"og:image недоступен: {error.__class__.__name__}") if not twitter_card: problems.append("нет twitter:card") for key, value in values.items(): print(f"{key}: {value or 'нет'}") print(f"twitter:card: {twitter_card or 'нет'}") if image_status is not None: print(f"og:image: HTTP {image_status}, {image_type or 'без Content-Type'}") if problems: print("Замечания:") for problem in problems: print(f" - {problem}") if args.json: report = {"url": args.url, "values": values, "twitter_card": twitter_card, "image_status": image_status, "problems": problems} args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт: {args.json}") return 0 if not problems else 1 if __name__ == "__main__": raise SystemExit(main())