# -*- coding: utf-8 -*-
import urllib.request, ssl, sys, io, re, gzip, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
SCTX = ssl.create_default_context()
SCTX.check_hostname = False
SCTX.verify_mode = ssl.CERT_NONE
items = [
    ("up-dsai-mse", "data-science-artificial-intelligence-mse", "Data Science and Artificial Intelligence, MSE"),
    ("up-mascs", "computer-science-mascs", "Computer Science, MASCS"),
    ("up-scicomp-mse", "scientific-computing-mse", "Scientific Computing, MSE"),
    ("up-mbds", "behavioral-decision-sciences-mbds", "Behavioral and Decision Sciences, MBDS"),
    ("up-biostat-ms", "epidemiology-biostatistics-biostatistics-ms", "Biostatistics, MS"),
]
out = open(r"D:\work buddy\2026-11-05-14-15-52\_extract82_out.txt", "w", encoding="utf-8")
for pid, slug, name in items:
    url = "https://catalog.upenn.edu/graduate/programs/%s/" % slug
    try:
        req = urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
        r = urllib.request.urlopen(req, timeout=25, context=SCTX)
        body = r.read().decode("utf-8", errors="replace")
        # 去标签
        text = re.sub(r"<script[\s\S]*?</script>", "", body)
        text = re.sub(r"<style[\s\S]*?</style>", "", text)
        text = re.sub(r"<[^>]+>", " ", text)
        text = re.sub(r"\s+", " ", text).strip()
        out.write("===== %s | %s | %s | %dKB =====\n" % (pid, slug, name, len(body)//1024))
        # 提取关键段：从 Overview 到 Requirements 结束
        # 找正文主区域
        m = re.search(r"(Overview|Program of Study|Degree Requirements|Admission|Curriculum)([\s\S]{0,8000})", text)
        if m:
            out.write(m.group(0)[:6000] + "\n\n")
        else:
            out.write(text[:5000] + "\n\n")
        print("OK %s %dKB" % (pid, len(body)//1024))
    except Exception as e:
        out.write("ERR %s %s\n\n" % (pid, e))
        print("ERR %s %s" % (pid, e))
    time.sleep(0.5)
out.close()
print("done")
