from __future__ import annotations import hashlib import io import re import tempfile from dataclasses import dataclass from datetime import date from pathlib import Path from typing import Iterable from urllib.parse import urljoin import fitz import httpx from bs4 import BeautifulSoup from docx import Document from .config import REQUEST_TIMEOUT_SECONDS, SITE_BASE_URL @dataclass(frozen=True) class NoticeLink: category: str title: str url: str publish_date: date | None @dataclass(frozen=True) class Attachment: name: str url: str text: str @dataclass(frozen=True) class ParsedDocument: category: str title: str url: str publish_date: date | None content: str attachments: list[Attachment] content_hash: str def fetch_text(url: str) -> str: headers = { "User-Agent": "CampusVerifyBot/0.1 (+public academic affairs sync)", } with httpx.Client(timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=True, headers=headers) as client: response = client.get(url) response.raise_for_status() response.encoding = "utf-8" return response.text def fetch_bytes(url: str) -> bytes: headers = { "User-Agent": "CampusVerifyBot/0.1 (+public academic affairs sync)", } with httpx.Client(timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=True, headers=headers) as client: response = client.get(url) response.raise_for_status() return response.content def clean_text(text: str) -> str: text = text.replace("\xa0", " ") text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip() def parse_date(value: str) -> date | None: match = re.search(r"(20\d{2})[-年/.](\d{1,2})[-月/.](\d{1,2})", value) if not match: return None year, month, day = (int(part) for part in match.groups()) return date(year, month, day) def absolute_url(base_url: str, href: str) -> str: return urljoin(base_url, href) def extract_notice_links(category: str, list_url: str) -> list[NoticeLink]: soup = BeautifulSoup(fetch_text(list_url), "lxml") notices: list[NoticeLink] = [] for anchor in soup.select(".lists li a[href], .lists a[href]"): href = anchor.get("href") if not href: continue url = absolute_url(list_url, href) if "/info/" not in url or not url.endswith(".htm"): continue span = anchor.find("span") publish_date = parse_date(span.get_text(" ", strip=True) if span else "") if span: span.extract() title = clean_text(anchor.get_text(" ", strip=True)) if title: notices.append(NoticeLink(category=category, title=title, url=url, publish_date=publish_date)) seen: set[str] = set() unique_notices: list[NoticeLink] = [] for notice in notices: if notice.url not in seen: unique_notices.append(notice) seen.add(notice.url) return unique_notices def discover_paged_urls(seed_url: str, max_pages: int) -> list[str]: urls = [seed_url] soup = BeautifulSoup(fetch_text(seed_url), "lxml") for anchor in soup.select(".p_pages a[href]"): href = anchor.get("href") if not href: continue url = absolute_url(seed_url, href) if url not in urls: urls.append(url) if len(urls) >= max_pages: break return urls def extract_docx_text(data: bytes) -> str: with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as tmp: tmp.write(data) tmp_path = Path(tmp.name) try: document = Document(str(tmp_path)) return clean_text("\n".join(paragraph.text for paragraph in document.paragraphs)) finally: tmp_path.unlink(missing_ok=True) def extract_pdf_text(data: bytes) -> str: document = fitz.open(stream=data, filetype="pdf") return clean_text("\n".join(page.get_text() for page in document)) def extract_attachment_text(name: str, data: bytes) -> str: suffix = Path(name).suffix.lower() if suffix == ".pdf": return extract_pdf_text(data) if suffix == ".docx": return extract_docx_text(data) return "" def extract_attachments(soup: BeautifulSoup, detail_url: str) -> list[Attachment]: attachments: list[Attachment] = [] for anchor in soup.select('a[href*="download.jsp"], a[href$=".pdf"], a[href$=".docx"]'): href = anchor.get("href") if not href: continue url = absolute_url(SITE_BASE_URL, href) if href.startswith("/") else absolute_url(detail_url, href) name = clean_text(anchor.get_text(" ", strip=True)) or Path(url).name try: data = fetch_bytes(url) text = extract_attachment_text(name, data) except Exception as exc: text = f"[附件解析失败: {exc}]" attachments.append(Attachment(name=name, url=url, text=text)) return attachments def parse_detail(notice: NoticeLink) -> ParsedDocument: html = fetch_text(notice.url) soup = BeautifulSoup(html, "lxml") title_node = soup.select_one(".art-tit h3, .cont-tit h3, h1") title = clean_text(title_node.get_text(" ", strip=True)) if title_node else notice.title date_node = soup.select_one(".art-tit p, .cont-tit p") publish_date = parse_date(date_node.get_text(" ", strip=True)) if date_node else notice.publish_date publish_date = publish_date or notice.publish_date content_node = soup.select_one(".v_news_content, #vsb_content_6, .art-body") content = clean_text(content_node.get_text("\n", strip=True)) if content_node else "" attachments = extract_attachments(soup, notice.url) hash_source = "\n".join([title, notice.url, content, *(item.text for item in attachments)]) content_hash = hashlib.sha256(hash_source.encode("utf-8")).hexdigest() return ParsedDocument( category=notice.category, title=title, url=notice.url, publish_date=publish_date, content=content, attachments=attachments, content_hash=content_hash, ) def iter_notices(category: str, seed_url: str, max_pages: int) -> Iterable[NoticeLink]: for list_url in discover_paged_urls(seed_url, max_pages): yield from extract_notice_links(category, list_url)