# -*- coding: utf-8 -*-
import io, sys, os, ssl, urllib.request, urllib.error, re, html as htmllib
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

def fetch(url, timeout=15):
    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=timeout,context=ctx)
    return r.status, r.read()

# 1. UT Psychology
print("===== UT psychology =====")
try:
    s,b=fetch("https://www.sgs.utoronto.ca/programs/psychology/")
    open("_43_ut_psych.html","wb").write(b)
    txt=b.decode("utf-8",errors="ignore")
    m=re.search(r'Quick Facts(.{200,8000}?)(?:</table>|</section>|Research Highlights|Admission Requirements|Faculty)', txt, re.S|re.I)
    if m:
        rows=re.findall(r'<tr[^>]*>(.*?)</tr>', m.group(1), re.S|re.I)
        for row in rows[:25]:
            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))
except Exception as e:
    print("ERR",e)

# 2. Cornell Chemistry 系站导航找 MS 路径
print("\n===== Cornell chemistry.cornell.edu 导航 =====")
try:
    s,b=fetch("https://chemistry.cornell.edu/graduate")
    open("_43_cornell_chem.html","wb").write(b)
    txt=b.decode("utf-8",errors="ignore")
    # 找所有链接
    links=re.findall(r'href="([^"]*(?:ms|master|graduate|program)[^"]*)"', txt, re.I)
    for l in sorted(set(links))[:20]:
        print("  link:",l)
except Exception as e:
    print("ERR",e)

# 3. NYU Biostatistics bulletin
print("\n===== NYU Biostatistics (GPH) bulletin =====")
try:
    s,b=fetch("https://bulletins.nyu.edu/graduate/global-public-health/programs/biostatistics-ms/")
    open("_43_nyu_biostat.html","wb").write(b)
    txt=b.decode("utf-8",errors="ignore")
    print("status",s,"len",len(b))
    # 找学位要求
    for kw in ["Biostatistics","MS","credit","admission","requirement","full-time","part-time"]:
        m=re.search(r'.{0,80}'+kw+r'.{0,150}', txt, re.I)
        if m:
            t=re.sub(r'<[^>]+>',' ',m.group(0))
            t=htmllib.unescape(re.sub(r'\s+',' ',t)).strip()
            print(f"  [{kw}] {t[:200]}")
except Exception as e:
    print("ERR",e)
