# -*- coding: utf-8 -*-
import urllib.request, ssl, re, sys, io, html as htmllib
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
ctx = ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"

def fetch(u):
    req = urllib.request.Request(u, headers={"User-Agent":UA, "Accept":"text/html,application/xhtml+xml"})
    r = urllib.request.urlopen(req, timeout=15, context=ctx)
    return r.status, r.read()

# 1. CEE MS 页
try:
    s, b = fetch("https://cee.rice.edu/prospective-current-students/graduate-programs/master-science-program")
    t = b.decode("utf-8", errors="ignore")
    t = htmllib.unescape(t)
    # 去标签取文本
    txt = re.sub(r"<script[\s\S]*?</script>", "", t, flags=re.I)
    txt = re.sub(r"<style[\s\S]*?</style>", "", txt, flags=re.I)
    txt = re.sub(r"<[^>]+>", " ", txt)
    txt = re.sub(r"\s+", " ", txt).strip()
    print(f"=== CEE MS ({s} {len(b)}B) ===")
    print(txt[:3000])
except Exception as e:
    print(f"CEE MS FAIL: {e}")

print()
# 2. CAAM 换 UA 重试
for u in [
    "https://caam.rice.edu/academics/graduate-programs/master-computational-and-applied-mathematics",
    "https://caam.rice.edu/graduate-programs",
    "https://caam.rice.edu/graduate-programs/ms-program",
]:
    try:
        s, b = fetch(u)
        t = b.decode("utf-8", errors="ignore")
        txt = re.sub(r"<script[\s\S]*?</script>", "", t, flags=re.I)
        txt = re.sub(r"<style[\s\S]*?</style>", "", txt, flags=re.I)
        txt = re.sub(r"<[^>]+>", " ", txt)
        txt = re.sub(r"\s+", " ", txt).strip()
        print(f"=== CAAM {u} ({s} {len(b)}B) ===")
        print(txt[:2000])
        break
    except Exception as e:
        print(f"CAAM {u} FAIL: {type(e).__name__} {str(e)[:80]}")
