from __future__ import annotations import argparse import hashlib import json import re import sys import time from collections import Counter from dataclasses import asdict from pathlib import Path from urllib import robotparser from urllib.parse import urljoin, urlsplit import httpx import yaml from bs4 import BeautifulSoup try: from advisors.cache import CacheRecord, CacheStore, RobotsPolicy, fetch_source_entry from advisors.discover import ( DiscoveredSource, _clean_anchor_text, _looks_like_faculty_list_text, _looks_like_unit_text, write_discovered_sources_yaml, ) from advisors.registry import SourceEntry, load_registry from advisors.url_utils import cache_key_for_url, host_matches, normalize_url except ModuleNotFoundError: sibling_src = Path(__file__).resolve().parents[2] / "Advisors" / "src" if sibling_src.exists(): sys.path.insert(0, str(sibling_src)) from advisors.cache import CacheRecord, CacheStore, RobotsPolicy, fetch_source_entry from advisors.discover import ( DiscoveredSource, _clean_anchor_text, _looks_like_faculty_list_text, _looks_like_unit_text, write_discovered_sources_yaml, ) from advisors.registry import SourceEntry, load_registry from advisors.url_utils import cache_key_for_url, host_matches, normalize_url else: raise UNIT_INDEX_TEXT_RE = re.compile( r"(院系设置|院系机构|院系部门|院系概览|学院设置|院部设置|教学单位|" r"教学机构|教学科研机构|学部院系|组织机构|机构设置|Schools|Colleges|Departments)", re.IGNORECASE, ) SKIP_URL_RE = re.compile( r"(?i)(?:javascript:|mailto:|#|/login|passport|webvpn|ivpn|auth/login|" r"\.(?:pdf|docx?|xlsx?|pptx?|zip|rar|jpg|jpeg|png|gif|svg)(?:$|[?#]))" ) ZH_NAME_RE = re.compile(r"^[\u4e00-\u9fff·]{2,4}$") PROFILE_PATH_RE = re.compile(r"/[A-Za-z0-9_.-]+/(?:zh_CN|en)/index\.htm$") WEBPLUS_PROFILE_PAGE_RE = re.compile( r"/(?:[0-9a-f]{2}/[0-9a-f]{2}|\d{4}/\d{4})/c\d+a\d+/page\.htm$", re.IGNORECASE, ) INFO_PROFILE_PAGE_RE = re.compile(r"/info/\d+/\d+\.htm$", re.IGNORECASE) HTML_PAGE_RE = re.compile(r"(?:/|\.)html?(?:$|[?#])", re.IGNORECASE) FACULTY_LIST_PAGINATION_TEXT_RE = re.compile(r"(下一页|尾页|末页|Next)", re.IGNORECASE) FACULTY_LIST_PAGINATION_URL_RE = re.compile( r"(?:/[^/]*list\d+\.htm$|(?:^|[?&])(?:PAGENUM|pageindex)=\d+|(?:^|[?&])totalpage=\d+)", re.IGNORECASE, ) FACULTY_SYSTEM_LIST_URL_RE = re.compile( r"/(?:pi|py)?jslb\.jsp\?|/(?:xyjslb|jsjs|jscx|xylb)\.jsp\?", re.IGNORECASE, ) IMAGESCALE_PROFILE_RE = re.compile( r"addimg\(\s*['\"][^'\"]*['\"]\s*,\s*['\"](?P[^'\"]+/(?:zh_CN|en)/index\.htm)['\"]\s*,\s*['\"](?P[^'\"]{1,40})['\"]", re.IGNORECASE, ) HTTPS_CANONICAL_HOSTS = { "faculty.dlut.edu.cn", "faculty-cn.tju.edu.cn", "faculty.scut.edu.cn", "faculty.scu.edu.cn", "faculty.uestc.edu.cn", "faculty.tju.edu.cn", "jszy.whu.edu.cn", } NON_NAME_SUBSTRINGS = ( "学院", "项目", "新闻", "通知", "公告", "队伍", "教育", "教学", "科研", "党团", "院友", "机构", "中心", "基地", "平台", "师资", "教师", "导师", "教授", "院士", "名医", "列表", "详情", "更多", "首页", "登录", "搜索", "招生", "招聘", "访客", "校历", "校友", "捐赠", "门户", "邮箱", "期刊", "平台", "看点", "风光", "生活", "文化", "党风", "党群", "党务", "党建", "理论", "工会", "论坛", "公文", "政策", "文件", "方案", "招考", "学生", "学工", "下载", "资料", "联系", "我们", "现任", "历任", "领导", "院长", "致辞", "院训", "院徽", "科研", "研究", "培养", "成果", "课程", "资源", "实验室", "管理", "服务", "规章", "制度", "毕业", "留影", "年报", "暑期", "萃英", "飞天", "访企", "拓岗", "实习", "信息", "招就", "动态", "专业", "推介", "人员", "分工", "常用", "历史", "沿革", "党史", "学校", "本科", "国际", "合作", "交流", "认证", "就业", "讲师", "青年", "全部", "二维码", ) TYPE_PRIORITY = { "university_home": 10, "unit_index": 20, "profile_portal": 20, "faculty_portal": 20, "unit_home": 30, "faculty_list": 40, "profile_index": 40, "profile_index_api": 40, "teacher_profile": 50, } def main() -> int: args = parse_args() registry = load_registry(args.sources) schools = set(args.school or []) universities = [ university for university in registry.universities if not schools or university.id in schools or university.name_zh in schools ] if not universities: raise SystemExit("No universities selected.") errors_path = Path(args.working_root) / "errors.tsv" errors_path.parent.mkdir(parents=True, exist_ok=True) if not errors_path.exists(): errors_path.write_text("school\tphase\tsource_id\turl\terror\n", encoding="utf-8") summary: list[dict[str, object]] = [] for university in universities: result = crawl_university(args, university, errors_path) summary.append(result) write_json(Path(args.working_root) / "crawl_summary.json", summary) print( f"{university.id}: records={result['cache_records']} " f"profiles={result['cache_types'].get('teacher_profile', 0)} " f"fetched={result['fetched']} skipped={result['skipped']} errors={result['errors']}", flush=True, ) write_json(Path(args.working_root) / "crawl_summary.json", summary) return 0 def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Cache official faculty pages for 985 universities.") parser.add_argument("--sources", default="configs/985_sources.yaml") parser.add_argument("--cache-root", default="data/cache") parser.add_argument("--working-root", default="data/working/985") parser.add_argument("--school", action="append", default=[], help="School id or Chinese name to process.") parser.add_argument("--rounds", type=int, default=2) parser.add_argument("--delay-seconds", type=float, default=0.2) parser.add_argument("--timeout-seconds", type=float, default=20.0) parser.add_argument("--ignore-robots", action="store_true") parser.add_argument("--robots-timeout-seconds", type=float, default=5.0) parser.add_argument("--refresh", action="store_true") parser.add_argument("--max-unit-indexes", type=int, default=40) parser.add_argument("--max-units", type=int, default=300) parser.add_argument("--max-faculty-lists", type=int, default=1200) parser.add_argument("--max-profiles", type=int, default=8000) parser.add_argument("--progress-every", type=int, default=200) return parser.parse_args() def crawl_university(args: argparse.Namespace, university, errors_path: Path) -> dict[str, object]: school_root = Path(args.cache_root) / university.id store = CacheStore(school_root) stats = Counter() robots_policy = TimeoutRobotsPolicy( "AdvisorsDataBot/0.1 (+https://github.com/open-data; research dataset)", timeout_seconds=args.robots_timeout_seconds, ) seed_entries = list(university.entries) fetch_many(args, seed_entries, store, robots_policy, stats, errors_path, university.id, "seed") for round_index in range(1, args.rounds + 1): round_dir = Path(args.working_root) / university.id / f"round-{round_index}" round_dir.mkdir(parents=True, exist_ok=True) unit_indexes = discover_unit_indexes_from_cache( school_root, university_name_zh=university.name_zh, source_id_prefix=f"{university.id}-unit-index", allowed_domains=list(university.allowed_domains), ) unit_indexes = limit_sources(unit_indexes, args.max_unit_indexes) write_sources( unit_indexes, round_dir / "discovered_unit_indexes.yaml", university, ) fetch_many( args, to_entries(unit_indexes, university), store, robots_policy, stats, errors_path, university.id, f"round-{round_index}:unit_index", ) units = discover_unit_homes_from_cache( school_root, university_name_zh=university.name_zh, source_id_prefix=f"{university.id}-unit", allowed_domains=list(university.allowed_domains), ) units = limit_sources(units, args.max_units) write_sources(units, round_dir / "discovered_units.yaml", university) fetch_many( args, to_entries(units, university), store, robots_policy, stats, errors_path, university.id, f"round-{round_index}:unit_home", ) faculty_lists = discover_faculty_lists_from_cache_safe( school_root, university_name_zh=university.name_zh, source_id_prefix=f"{university.id}-faculty-list", allowed_domains=list(university.allowed_domains), ) faculty_lists = limit_sources(faculty_lists, args.max_faculty_lists) write_sources(faculty_lists, round_dir / "discovered_faculty_lists.yaml", university) fetch_many( args, to_entries(faculty_lists, university), store, robots_policy, stats, errors_path, university.id, f"round-{round_index}:faculty_list", ) profiles = discover_profiles_from_cache_safe( school_root, university_name_zh=university.name_zh, source_id_prefix=f"{university.id}-profile", allowed_domains=list(university.allowed_domains), ) profiles = limit_sources(profiles, args.max_profiles) write_sources(profiles, round_dir / "discovered_profiles.yaml", university) fetch_many( args, to_entries(profiles, university), store, robots_policy, stats, errors_path, university.id, f"round-{round_index}:teacher_profile", ) cache_types = count_cache_types(store) return { "school": university.id, "university": university.name_zh, "fetched": stats["fetched"], "skipped": stats["skipped"], "errors": stats["errors"], "cache_records": sum(cache_types.values()), "cache_types": dict(cache_types), } def fetch_many( args: argparse.Namespace, entries: list[SourceEntry], store: CacheStore, robots_policy: RobotsPolicy, stats: Counter, errors_path: Path, school_id: str, phase: str, ) -> None: seen: set[str] = set() processed = 0 total = len(entries) for entry in entries: normalized = entry.normalized_url if normalized in seen: continue seen.add(normalized) processed += 1 try: status = fetch_one(args, entry, store, robots_policy) stats[status] += 1 except Exception as exc: # noqa: BLE001 - long crawls should keep moving. stats["errors"] += 1 append_error(errors_path, school_id, phase, entry.id, entry.url, repr(exc)) if args.delay_seconds > 0 and stats["fetched"]: time.sleep(args.delay_seconds) if args.progress_every > 0 and processed % args.progress_every == 0: print( f"{school_id} {phase}: processed {processed}/{total} " f"fetched={stats['fetched']} skipped={stats['skipped']} errors={stats['errors']}", flush=True, ) def fetch_one( args: argparse.Namespace, entry: SourceEntry, store: CacheStore, robots_policy: RobotsPolicy, ) -> str: existing = load_existing_record(store.root, entry.normalized_url) if existing and not should_refetch(existing, entry, args.refresh): return "skipped" fetch_source_entry( entry, store, timeout_seconds=args.timeout_seconds, respect_robots=not args.ignore_robots, robots_policy=robots_policy, ) return "fetched" class TimeoutRobotsPolicy: def __init__(self, user_agent: str, *, timeout_seconds: float): self.user_agent = user_agent self.timeout_seconds = timeout_seconds self._parsers: dict[str, robotparser.RobotFileParser] = {} def can_fetch(self, url: str) -> bool: split = urlsplit(url) base = f"{split.scheme}://{split.netloc}" parser = self._parsers.get(base) if parser is None: parser = self._read_parser(base) self._parsers[base] = parser return parser.can_fetch(self.user_agent, url) def _read_parser(self, base: str) -> robotparser.RobotFileParser: robots_url = urljoin(base, "/robots.txt") parser = robotparser.RobotFileParser(robots_url) try: response = httpx.get( robots_url, follow_redirects=True, timeout=self.timeout_seconds, headers={"User-Agent": self.user_agent}, ) except httpx.HTTPError: parser.allow_all = True return parser if response.status_code in {401, 403}: parser.disallow_all = True return parser if 400 <= response.status_code < 500: parser.allow_all = True return parser parser.parse(response.text.splitlines()) return parser def should_refetch(existing: CacheRecord, entry: SourceEntry, refresh: bool) -> bool: if refresh: return True existing_priority = TYPE_PRIORITY.get(existing.source_type, 0) wanted_priority = TYPE_PRIORITY.get(entry.type, 0) if wanted_priority > existing_priority: return True return False def load_existing_record(cache_root: Path, url: str) -> CacheRecord | None: key = cache_key_for_url(normalize_url(url)) path = cache_root / "metadata" / key[:2] / key[2:4] / f"{key}.json" if not path.exists(): return None return CacheRecord(**json.loads(path.read_text(encoding="utf-8"))) def discover_unit_indexes_from_cache( cache_root: str | Path, *, university_name_zh: str, source_id_prefix: str, allowed_domains: list[str], ) -> list[DiscoveredSource]: records = list(CacheStore(cache_root).iter_records()) discovered: dict[str, DiscoveredSource] = {} for record in records: if record.university != university_name_zh: continue if record.source_type not in {"university_home", "unit_index"}: continue for url, text in iter_links(record, allowed_domains): if not UNIT_INDEX_TEXT_RE.search(text): continue discovered.setdefault( url, DiscoveredSource( id=source_id(url, prefix=source_id_prefix), url=url, type="unit_index", department=None, status="discovered", notes=f"Discovered from {record.source_type} page.", discovered_from=record.source_url, anchor_text=text, ), ) return sorted(discovered.values(), key=lambda item: item.url) def discover_unit_homes_from_cache( cache_root: str | Path, *, university_name_zh: str, source_id_prefix: str, allowed_domains: list[str], ) -> list[DiscoveredSource]: records = list(CacheStore(cache_root).iter_records()) discovered: dict[str, DiscoveredSource] = {} for record in records: if record.university != university_name_zh: continue if record.source_type not in {"university_home", "unit_index"}: continue for url, text in iter_links(record, allowed_domains): if not _looks_like_unit_text(text): continue discovered.setdefault( url, DiscoveredSource( id=source_id(url, prefix=source_id_prefix), url=url, type="unit_home", department=text, status="discovered", notes=f"Discovered from {record.source_type} page.", discovered_from=record.source_url, anchor_text=text, ), ) return sorted(discovered.values(), key=lambda item: item.url) def discover_faculty_lists_from_cache_safe( cache_root: str | Path, *, university_name_zh: str, source_id_prefix: str, allowed_domains: list[str], ) -> list[DiscoveredSource]: records = list(CacheStore(cache_root).iter_records()) discovered: dict[str, DiscoveredSource] = {} for record in records: if record.university != university_name_zh: continue if record.source_type not in {"unit_home", "faculty_portal", "profile_portal", "unit_index", "faculty_list"}: continue for url, text in iter_links(record, allowed_domains): is_faculty_list = _looks_like_faculty_list_text(text) is_pagination = ( record.source_type == "faculty_list" and FACULTY_LIST_PAGINATION_TEXT_RE.search(text) and FACULTY_LIST_PAGINATION_URL_RE.search(urlsplit(url).path) ) or ( record.source_type == "faculty_list" and FACULTY_LIST_PAGINATION_TEXT_RE.search(text) and FACULTY_LIST_PAGINATION_URL_RE.search(urlsplit(url).query) ) is_faculty_system_list = ( record.source_type in {"profile_portal", "faculty_portal", "faculty_list"} and FACULTY_SYSTEM_LIST_URL_RE.search(urlsplit(url).path + "?" + urlsplit(url).query) ) if not is_faculty_list and not is_pagination and not is_faculty_system_list: continue discovered.setdefault( url, DiscoveredSource( id=source_id(url, prefix=source_id_prefix), url=url, type="faculty_list", department=record.department, status="discovered", notes=f"Discovered from {record.source_type} page.", discovered_from=record.source_url, anchor_text=text, ), ) return sorted(discovered.values(), key=lambda item: item.url) def discover_profiles_from_cache_safe( cache_root: str | Path, *, university_name_zh: str, source_id_prefix: str, allowed_domains: list[str], ) -> list[DiscoveredSource]: records = list(CacheStore(cache_root).iter_records()) discovered: dict[str, DiscoveredSource] = {} for record in records: if record.university != university_name_zh: continue if record.source_type not in {"faculty_list", "profile_index", "profile_portal"}: continue for url, text in iter_links(record, allowed_domains): name_hint = name_hint_from_anchor(text) if looks_like_profile_url(url) or ( name_hint and (looks_like_faculty_detail_link(url) or looks_like_html_page(url)) ): discovered.setdefault( url, DiscoveredSource( id=source_id(url, prefix=source_id_prefix), url=url, type="teacher_profile", department=record.department, status="discovered", notes=f"Discovered from {record.source_type} page.", discovered_from=record.source_url, anchor_text=name_hint or text, ), ) return sorted(discovered.values(), key=lambda item: item.url) def iter_links(record: CacheRecord, allowed_domains: list[str]) -> list[tuple[str, str]]: if not record.cache_path: return [] html_path = Path(record.cache_path) if not html_path.exists(): return [] try: html = html_path.read_text(encoding=record.encoding or "utf-8", errors="replace") except OSError: return [] soup = BeautifulSoup(html, "html.parser") links: list[tuple[str, str]] = [] for anchor in soup.find_all("a", href=True): href = anchor["href"].strip() if SKIP_URL_RE.search(href): continue text = _clean_anchor_text(anchor.get_text(" ", strip=True)) if not text or len(text) > 80: continue try: url = canonicalize_discovered_url(normalize_url(urljoin(record.final_url or record.source_url, href))) except ValueError: continue if SKIP_URL_RE.search(url): continue host = urlsplit(url).hostname or "" if not host_matches(host, allowed_domains): continue links.append((url, text)) links.extend(iter_embedded_profile_links(html, record.final_url or record.source_url, allowed_domains)) return links def iter_embedded_profile_links(html: str, base_url: str, allowed_domains: list[str]) -> list[tuple[str, str]]: links: list[tuple[str, str]] = [] for match in IMAGESCALE_PROFILE_RE.finditer(html): text = _clean_anchor_text(match.group("text")) if not text or len(text) > 40: continue try: url = canonicalize_discovered_url(normalize_url(urljoin(base_url, match.group("href")))) except ValueError: continue host = urlsplit(url).hostname or "" if host_matches(host, allowed_domains): links.append((url, text)) return links def looks_like_profile_url(url: str) -> bool: return bool(PROFILE_PATH_RE.search(urlsplit(url).path)) def canonicalize_discovered_url(url: str) -> str: split = urlsplit(url) host = split.hostname or "" if split.scheme == "http" and host in HTTPS_CANONICAL_HOSTS: return "https://" + split.netloc + split.path + (f"?{split.query}" if split.query else "") return url def looks_like_faculty_detail_link(url: str) -> bool: path = urlsplit(url).path return bool(INFO_PROFILE_PAGE_RE.search(path) or WEBPLUS_PROFILE_PAGE_RE.search(path)) def looks_like_html_page(url: str) -> bool: split = urlsplit(url) path = split.path if re.search(r"(?i)(?:^|/)(?:index|news|kxyj|zs|zs1|xxg|yxsz|szdw1)(?:/|\\.|$)", path): return False if HTML_PAGE_RE.search(path): return True suffix = Path(path).suffix.lower() return not suffix and path.rstrip("/").count("/") >= 1 def name_hint_from_anchor(anchor_text: str) -> str | None: text = _clean_anchor_text(anchor_text) text = re.sub(r"[((].*?[))]", "", text) text = re.sub(r"\s+", "", text) repeat_match = re.match(r"^([\u4e00-\u9fff·]{2,4})\1", text) if repeat_match and looks_like_name_anchor(repeat_match.group(1)): return repeat_match.group(1) title_match = re.match( r"^([\u4e00-\u9fff·]{2,4})(?:教授|副教授|研究员|副研究员|讲师|助理教授|" r"助理研究员|博士生导师|硕士生导师)", text, ) if title_match and looks_like_name_anchor(title_match.group(1)): return title_match.group(1) return text if looks_like_name_anchor(text) else None def looks_like_name_anchor(anchor_text: str) -> bool: return bool( ZH_NAME_RE.fullmatch(anchor_text) and not any(token in anchor_text for token in NON_NAME_SUBSTRINGS) and not anchor_text.lower().startswith(("http://", "https://")) ) def to_entries(sources: list[DiscoveredSource], university) -> list[SourceEntry]: return [ SourceEntry( id=source.id, university_id=university.id, university_name_zh=university.name_zh, university_name_en=university.name_en, url=source.url, type=source.type, allowed_domains=university.allowed_domains, department=source.department, status=source.status, notes=f"{source.notes} anchor={source.anchor_text!r}; from={source.discovered_from}", name_hint=source.anchor_text if source.type == "teacher_profile" else None, ) for source in sources ] def write_sources(sources: list[DiscoveredSource], path: Path, university) -> None: if not sources: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( yaml.safe_dump( { "version": 1, "universities": [ { "id": university.id, "name_zh": university.name_zh, "name_en": university.name_en, "allowed_domains": list(university.allowed_domains), "entries": [], } ], }, allow_unicode=True, sort_keys=False, ), encoding="utf-8", ) return write_discovered_sources_yaml( sources, path, university_id=university.id, university_name_zh=university.name_zh, university_name_en=university.name_en, allowed_domains=list(university.allowed_domains), ) def limit_sources(sources: list[DiscoveredSource], limit: int | None) -> list[DiscoveredSource]: if limit is None or limit <= 0: return sources return sources[:limit] def source_id(url: str, *, prefix: str) -> str: split = urlsplit(url) slug = re.sub(r"[^A-Za-z0-9]+", "-", f"{split.netloc}{split.path}").strip("-").lower() digest = hashlib.sha1(url.encode("utf-8")).hexdigest()[:8] return f"{prefix}-{slug[:72]}-{digest}" def count_cache_types(store: CacheStore) -> Counter: counts: Counter = Counter() for record in store.iter_records(): counts[record.source_type] += 1 return counts def append_error(path: Path, school_id: str, phase: str, source_id_: str, url: str, error: str) -> None: safe_error = error.replace("\t", " ").replace("\n", " ") with path.open("a", encoding="utf-8") as handle: handle.write(f"{school_id}\t{phase}\t{source_id_}\t{url}\t{safe_error}\n") def write_json(path: Path, data: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") if __name__ == "__main__": raise SystemExit(main())