# -*- coding: utf-8 -*-
import sys, io, os, requests, re, concurrent.futures as cf
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
BASE = r"D:\work buddy\2026-11-05-14-15-52"
H = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"}
URLS = {
 "wlu-ucal-http": "http://ucalendar.uwaterloo.ca/2526/COURSE/course-STAT.html",
 "wlu-ucal-www": "https://www.ucalendar.uwaterloo.ca/2526/COURSE/course-STAT.html",
 "wlu-grad-idx": "https://uwaterloo.ca/graduate-studies-post-doctoral-studies/graduate-programs",
 "wlu-grad2": "https://uwaterloo.ca/future-graduate-students/programs",
 "wlu-mdsai2": "https://uwaterloo.ca/graduate-studies-post-doctoral-studies/programs/data-science-and-artificial-intelligence-mdsai",
 "wlu-cs-mmath2": "https://uwaterloo.ca/graduate-studies-post-doctoral-studies/programs/computer-science-mmath",
 "wlu-stat-mmath2": "https://uwaterloo.ca/graduate-studies-post-doctoral-studies/programs/statistics-mmath",
 "wlu-fees": "https://uwaterloo.ca/finance/student-financial-services/tuition-fees",
 "brown-ds": "https://dsi.brown.edu/academics/graduate-study/master-data-science",
 "brown-bio": "https://biostatistics.sph.brown.edu/academics/graduate-programs",
}
def go(kv):
    k, u = kv
    try:
        r = requests.get(u, headers=H, timeout=20, allow_redirects=True)
        body = r.text
        open(BASE + "\\cache\\r348-" + k + ".html", "w", encoding="utf-8", errors="replace").write(body)
        return k, r.status_code, len(body), r.url
    except Exception as e:
        return k, "ERR", str(e)[:70], u
with cf.ThreadPoolExecutor(max_workers=8) as ex:
    for k, st, ln, u in ex.map(go, URLS.items()):
        print(f"{st} {ln:7} {k:16s} {u}")

# brown-courses 文本抽样
p = BASE + r"\cache\r348-brown-courses.html"
if os.path.exists(p):
    t = open(p, encoding="utf-8", errors="replace").read()
    t = re.sub(r"<script.*?</script>", " ", t, flags=re.S)
    t = re.sub(r"<[^>]+>", " ", t)
    t = re.sub(r"\s+", " ", t)
    print("\nBROWN COURSES len", len(t))
    print(t[:1500])
    print("--- CS codes:", len(re.findall(r"\bCS\s?\d{4}\b", t)), re.findall(r"\bCS\s?\d{4}\b", t)[:12])
