# -*- coding: utf-8 -*-
import urllib.request, ssl, re, io, sys, os
sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding="utf-8")
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
url="https://uwaterloo.ca/future-graduate-students/programs/by-faculty/engineering/management-science-and-engineering-master-applied-science"
req=urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0"})
try:
    html=urllib.request.urlopen(req, timeout=25, context=ctx).read().decode("utf-8","ignore")
    print("LEN", len(html), "URL", url)
    txt=re.sub(r"<script[\s\S]*?</script>"," ",html)
    txt=re.sub(r"<style[\s\S]*?</style>"," ",txt)
    txt=re.sub(r"<[^>]+>"," ",txt)
    txt=re.sub(r"&nbsp;"," ",txt); txt=re.sub(r"&amp;","&",txt); txt=re.sub(r"&#039;","'",txt)
    txt=re.sub(r"\s+"," ",txt)
    for kw in ["Delivery","Program type","Program name","Duration","Term","Admission","Average","honours","TOEFL","IELTS","GRE","GMAT","reference","Personal","transcript","Resume","Statement","Tuition","Funding","Research","coursework","thesis","Thesis","Co-op","Deadline","deadline","September","January","May"]:
        for m in re.finditer(kw, txt):
            s=max(0,m.start()-90); e=min(len(txt),m.end()+150)
            print("…", txt[s:e].strip())
            break
except Exception as ex:
    print("ERR", type(ex).__name__, ex)
