# -*- coding: utf-8 -*-
import io, sys, re, ssl, urllib.request, os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
BASE = 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=20):
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36"})
    with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r:
        raw = r.read()
        enc = r.headers.get_content_charset() or "utf-8"
        return r.status, raw.decode(enc, errors="replace"), url

urls = [
    "https://gsas.harvard.edu/program/data-science",
]
for u in urls:
    try:
        st, html, final = fetch(u)
        print("=== ", st, len(html), final)
        # 去标签正文
        body = re.sub(r"<script.*?</script>", " ", html, flags=re.S)
        body = re.sub(r"<style.*?</style>", " ", body, flags=re.S)
        text = re.sub(r"<[^>]+>", " ", body)
        text = re.sub(r"\s+", " ", text).strip()
        print("正文长度:", len(text))
        print(text[:3500])
        print("\n--- 站内链接 ---")
        for href, t in re.findall(r'href="([^"]+)"[^>]*>([^<]{2,60})</a>', html)[:60]:
            if any(k in href for k in ["admiss","tuition","deadline","requirement","course","program","financial","international","application","data-science"]):
                print(" ", href, "|", t.strip())
        open(os.path.join(BASE, "_hds_page.html"), "w", encoding="utf-8").write(html)
    except Exception as e:
        print("ERR", u, repr(e))
