#!/usr/bin/env python3 """Проверка alt-текстов изображений.""" from __future__ import annotations import argparse import json import re from collections import Counter from pathlib import Path import requests from bs4 import BeautifulSoup FILE_LIKE = re.compile(r"\.(png|jpe?g|gif|webp|svg|avif)$", re.IGNORECASE) def main() -> int: parser = argparse.ArgumentParser(description="Проверить alt изображений") parser.add_argument("url", nargs="?", default="https://example.com/") parser.add_argument("--max-length", type=int, default=125) parser.add_argument("--timeout", type=float, default=15.0) parser.add_argument("--json", type=Path, help="Сохранить отчёт") args = parser.parse_args() try: response = requests.get(args.url, timeout=args.timeout, headers={"User-Agent": "popovdev-scriptdock/1.0"}) response.raise_for_status() except requests.RequestException as error: print(f"Не удалось загрузить страницу: {error}") return 2 soup = BeautifulSoup(response.content, "html.parser") images = soup.find_all("img") missing = [] empty = [] long_text = [] file_like = [] values = [] for image in images: src = image.get("src", "") if "alt" not in image.attrs: missing.append(src) continue alt = (image.get("alt") or "").strip() if not alt: empty.append(src) continue values.append(alt) if len(alt) > args.max_length: long_text.append({"src": src, "alt": alt}) if FILE_LIKE.search(alt): file_like.append({"src": src, "alt": alt}) duplicates = {text: count for text, count in Counter(values).items() if count > 1} print(f"Изображений: {len(images)}") print(f"Без alt: {len(missing)}") print(f"Пустой alt: {len(empty)}") print(f"Слишком длинный alt: {len(long_text)}") print(f"Похоже на имя файла: {len(file_like)}") print(f"Повторяющихся alt: {len(duplicates)}") for src in missing[:10]: print(f" нет alt: {src}") for item in long_text[:10]: print(f" длинный alt ({len(item['alt'])}): {item['src']}") report = { "images": len(images), "missing": missing, "empty": empty, "long": long_text, "file_like": file_like, "duplicates": duplicates, } if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт: {args.json}") return 0 if not missing else 1 if __name__ == "__main__": raise SystemExit(main())