# -*- coding: utf-8 -*-
import urllib.request, ssl, sys, io, time, traceback
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
slugs = [
 "applied-positive-psychology-mapp",
 "government-administration-mpa",
 "international-mpa",
 "health-care-innovation-mhci",
 "public-health-mph",
]
for s in slugs:
    url = f"https://catalog.upenn.edu/graduate/programs/{s}/"
    saved = False
    for attempt in range(6):
        try:
            req = urllib.request.Request(url, headers={
                "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36",
                "Referer":"https://catalog.upenn.edu/graduate/programs/",
                "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Accept-Language":"en-US,en;q=0.9",
                "Connection":"keep-alive",
            })
            r = urllib.request.urlopen(req, timeout=30, context=SCTX)
            body = r.read()
            if r.status == 200 and len(body) > 5000:
                text = body.decode("utf-8","ignore")
                open(f"_raw_{s}.html","w",encoding="utf-8").write(text)
                print(s, "OK", r.status, len(text), "attempt", attempt)
                saved = True
                break
            else:
                print(s, "attempt", attempt, "status", r.status, "len", len(body))
                time.sleep(3)
        except Exception as e:
            print(s, "attempt", attempt, "ERR", repr(e)[:100])
            time.sleep(3)
    if not saved:
        print(s, "GIVE UP")
