|
| 1 | +import re |
| 2 | +from urllib2 import urlopen |
| 3 | +from bs4 import BeautifulSoup |
| 4 | + |
| 5 | +def fetch_soup (url): |
| 6 | + response = urlopen(url) |
| 7 | + return BeautifulSoup(response.read(), 'html.parser') |
| 8 | + |
| 9 | +def enforce (condition, msg, *args): |
| 10 | + if not condition: |
| 11 | + raise Exception(msg % args) |
| 12 | + |
| 13 | +def parse_department_link (a): |
| 14 | + href = a['href'] #if 'href' in a else '' |
| 15 | + #title = a['title'] if 'title' in a else '' |
| 16 | + match = re.match(r'program.statements/([a-z]+\.html)', href) |
| 17 | + enforce(match, "Unexpected link url: '%s'", href) |
| 18 | + text = a.text |
| 19 | + if text: |
| 20 | + return text, href |
| 21 | + |
| 22 | +def parse_department_links (links): |
| 23 | + for link in links: |
| 24 | + result = parse_department_link(link) |
| 25 | + if result: |
| 26 | + yield result |
| 27 | + |
| 28 | +def fetch_department_urls (base_url = 'https://registrar.ucsc.edu/catalog/programs-courses'): |
| 29 | + index_url = '%s/index.html'%base_url |
| 30 | + soup = fetch_soup(index_url) |
| 31 | + dept_anchor = soup.find('a', id='departments') |
| 32 | + enforce(dept_anchor, "Could not find '%s/#departments'", index_url) |
| 33 | + header = dept_anchor.parent |
| 34 | + enforce(header.name == "h2", "Unexpected: is not a h2 tag (got '%s')", header.name) |
| 35 | + table = header.findNext('td') |
| 36 | + enforce(table.name == "td", "Expected element after heading to be table, not '%s'", table.name) |
| 37 | + return {k: '%s/%s'%(base_url, v) for k, v in parse_department_links(table.find_all('a'))} |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == '__main__': |
| 41 | + result = fetch_department_urls() |
| 42 | + print(result) |
0 commit comments