# -*- coding: utf-8 -*-
import ssl, io, sys, urllib.request, re, html
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
BASE = r"D:\work buddy\2026-11-05-14-15-52"

def fetch(u):
    req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
    r = urllib.request.urlopen(req, timeout=15, context=ctx)
    return r.read().decode("utf-8", "ignore")

def strip(t):
    t = re.sub(r"<script.*?</script>", " ", t, flags=re.S)
    t = re.sub(r"<style.*?</style>", " ", t, flags=re.S)
    t = re.sub(r"<[^>]+>", " ", t)
    t = html.unescape(t)
    return re.sub(r"\s+", " ", t).strip()

for tag, u in [("duke_econ", "https://gradschool.duke.edu/academics/programs-degrees/economics-masters/"),
               ("harvard_cse", "https://gsas.harvard.edu/program/computational-science-and-engineering"),
               ("harvard_eas", "https://gsas.harvard.edu/program/engineering-and-applied-sciences")]:
    try:
        h = fetch(u)
        open(BASE + rf"_{tag}.html", "w", encoding="utf-8").write(h)
        body = strip(h)
        print(f"=== {tag} 正文长度 {len(body)} ===")
        print(body[:1200])
        print()
    except Exception as e:
        print(f"ERR {tag} {type(e).__name__} {str(e)[:80]}")
