# -*- coding: utf-8 -*-
import io, sys, os, ssl, urllib.request, html as htmllib, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE

slugs=["computer-science","applied-computing","public-health","kinesiology","materials-science"]
for s in slugs:
    url=f"https://www.sgs.utoronto.ca/programs/{s}/"
    req=urllib.request.Request(url,headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0"})
    r=urllib.request.urlopen(req,timeout=20,context=ctx)
    b=r.read()
    open(f"_42_{s}.html","wb").write(b)
    txt=b.decode("utf-8",errors="ignore")
    # 提取 Quick Facts 段
    # 找 table 结构
    m=re.search(r'Quick Facts(.{200,8000}?)(?:</table>|</section>|Research Highlights|Admission Requirements|Faculty)', txt, re.S|re.I)
    if m:
        seg=m.group(1)
        # 提取 tr/td
        rows=re.findall(r'<tr[^>]*>(.*?)</tr>', seg, re.S|re.I)
        print(f"\n===== {s} ({len(b)}B) =====")
        for row in rows[:30]:
            tds=re.findall(r'<td[^>]*>(.*?)</td>', row, re.S|re.I)
            tds=[re.sub(r'<[^>]+>','',x).strip() for x in tds]
            tds=[htmllib.unescape(x) for x in tds if x.strip()]
            if tds: print(" | ".join(tds))
    else:
        print(f"\n===== {s} ({len(b)}B) Quick Facts not found =====")
        # 尝试找 Program Requirements 等关键段
        for kw in ["Master of","MSc","MA","MEng","MASc","MPH","MHSc","duration","Minimum","deadline","English","Tuition"]:
            mm=re.search(r'.{0,100}'+kw+r'.{0,200}', txt, re.I)
            if mm:
                t=re.sub(r'<[^>]+>',' ',mm.group(0))
                t=htmllib.unescape(re.sub(r'\s+',' ',t)).strip()
                print(f"  [{kw}] {t[:200]}")
