#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""批量探测院校官网项目目录页：状态码、可解析的项目链接数、样例。"""
import re, sys, json, os
import urllib.request, urllib.error, ssl

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
HDRS = {
    "User-Agent": UA,
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.9",
}
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE


def get(url, timeout=30):
    req = urllib.request.Request(url, headers=HDRS)
    with urllib.request.urlopen(req, timeout=timeout, context=CTX) as r:
        raw = r.read()
        code = r.getcode()
    for enc in ("utf-8", "latin-1"):
        try:
            return code, raw.decode(enc)
        except Exception:
            continue
    return code, raw.decode("utf-8", "ignore")


LINK_RE = re.compile(r'<a\b[^>]*href="([^"]+)"[^>]*>(.*?)</a>', re.S | re.I)


def strip(s):
    s = re.sub(r"<[^>]+>", " ", s)
    s = re.sub(r"&nbsp;|&amp;", " ", s)
    return re.sub(r"\s+", " ", s).strip()


def links(html, base):
    out = []
    for href, txt in LINK_RE.findall(html):
        t = strip(txt)
        if not t or len(t) > 110:
            continue
        if href.startswith("#") or href.startswith("javascript"):
            continue
        if href.startswith("/"):
            href = base.rstrip("/") + href
        out.append((href, t))
    return out


def score(urls_text):
    """判断一页是否像项目目录：含学位关键词的链接数"""
    n = 0
    for href, t in urls_text:
        if re.search(r"\b(M\.?S\.?|M\.?Eng|MA|MBA|MPP|MPH|PhD|Master|Doctor|Graduate)\b", t, re.I):
            n += 1
    return n


def main(targets):
    for name, url in targets:
        try:
            code, h = get(url)
        except Exception as e:
            print(f"[ERR ] {name:<16} {type(e).__name__}: {str(e)[:70]}")
            continue
        ls = links(h, url)
        sc = score(ls)
        print(f"[{code}] {name:<16} len={len(h):>7} links={len(ls):>4} deg={sc:>4}  {url}")
        if sc >= 3:
            seen = set()
            shown = 0
            for href, t in ls:
                if not re.search(r"\b(M\.?S\.?|M\.?Eng|MA|MBA|PhD|Master|Doctor)\b", t, re.I):
                    continue
                if t in seen:
                    continue
                seen.add(t)
                print(f"        · {t[:70]:<72} {href[:100]}")
                shown += 1
                if shown >= 6:
                    break


if __name__ == "__main__":
    if sys.argv[1:]:
        tg = [tuple(x.split("=", 1)) for x in sys.argv[1:]]
    else:
        tg = []
    main(tg)
