# -*- coding: utf-8 -*-
import urllib.request, ssl, gzip, io, sys, re, 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

url = "https://catalog.upenn.edu/graduate/programs/international-studies-ma/"
for attempt in range(3):
    req = urllib.request.Request(url, headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Referer":"https://catalog.upenn.edu/graduate/programs/",
    })
    try:
        with urllib.request.urlopen(req, timeout=25, context=SCTX) as r:
            data = r.read()
            enc = r.headers.get("Content-Encoding","")
            if enc == "gzip":
                data = gzip.decompress(data)
            txt = data.decode("utf-8", errors="replace")
            if r.status == 202 or len(txt) < 100:
                time.sleep(2); continue
            break
    except Exception as e:
        time.sleep(2); continue

m = re.search(r'<div id="texttab"[^>]*>([\s\S]*?)</div>\s*</div>\s*</div>', txt)
body = m.group(1) if m else txt
body = re.sub(r'<[^>]+>', ' ', body)
body = re.sub(r'\s+', ' ', body).strip()
# 找 overview/Lauder/MBA/dual/full-time
for kw in ["Lauder","MBA","dual","Wharton","full-time","part-time","professional","degree","Admission","admission","concurrent","joint"]:
    for mm in re.finditer(r'.{60}'+re.escape(kw)+r'.{180}', body, re.I):
        print(f"[{kw}] {mm.group(0)[:280]}")
        print("---")
