import collections import sys import hashlib import queue import os import urllib.parse import re import requests import bs4 _WEB_CACHE_DIR = '.web-cache' def _extract_secondary_progression(content): doc = bs4.BeautifulSoup(content, 'html.parser') table = doc.find(id='sch1') print(table.text) def _process_school(content, schools, **_): doc = bs4.BeautifulSoup(content, 'html.parser') data = { 'name': doc.find(id='area1').h1.get_text().strip() } for link in doc.find_all('a'): url = link.get('href') if url.startswith('https://www.google.com/maps/search/?'): parsed = urllib.parse.urlparse(link.get('href')) params = urllib.parse.parse_qs(parsed.query) if 'query' in params: latlon = params['query'][0].split(',') data['lat'] = float(latlon[0].strip()) data['lon'] = float(latlon[1].strip()) elif url.endswith('/college-progression'): content = fetch(url) data['progression'] = _extract_secondary_progression(content) # print(doc.area1) a1 = doc.find(id='area1').get_text() for line in a1.splitlines(): if line.startswith('Primary School'): data['type'] = 'primary' elif line.startswith('Secondary School'): data['type'] = 'secondary' elif line.startswith('Post Primary School'): data['type'] = 'secondary' elif line.startswith('Ethos: '): ethos = line[7:].split(',')[0].strip(' \xa0') ethos = ethos.lower() ethos = ethos.replace('-', '').replace('inter','multi') if '\xa0' in ethos: ethos = ethos.split('\xa0')[0].strip() if ethos and ethos not in ['other/unknown']: data['ethos'] = ethos elif line.startswith('Fees: Yes '): try: data['fee'] = int(line[11:].replace(',','').replace(' per year','')) except ValueError: data['fee'] = line[11:].replace(',','').replace(' per year','') schools.append(data) def _process_index(content, q, **_): doc = bs4.BeautifulSoup(content, 'html.parser') for link in doc.find_all('a'): url = link.get('href').lower() q.append(url) _URL_PREFIXES = { '/articles/primary-schools-in-ireland-by-county': _process_index, # '/primary-schools-in-ireland': _process_index, '/primary-schools-in-ireland/primary-dublin': _process_index, '/articles/secondary-schools-in-ireland-by-county': _process_index, # '/secondary-schools-in-ireland': _process_index, '/secondary-schools-in-ireland/dublin': _process_index, '/school/': _process_school, } def fetch(url): if not os.path.isdir(_WEB_CACHE_DIR): os.mkdir(_WEB_CACHE_DIR) if url.startswith('/'): url = 'https://www.schooldays.ie' + url fname = os.path.join(_WEB_CACHE_DIR, hashlib.md5(url.encode('utf-8')).hexdigest()) print((url, fname)) if os.path.isfile(fname): with open(fname) as f: return f.read() resp = requests.get(url, timeout=20) if resp.status_code == 200: with open(fname, 'wb') as f: f.write(resp.content) return resp.content else: raise Exception('%i: %s' % (resp.status_code, url)) def run(): q = None if len(sys.argv) > 1: q = queue.deque(sys.argv[1:]) else: q = queue.deque([ 'https://www.schooldays.ie/articles/primary-schools-in-ireland-by-county', 'https://www.schooldays.ie/articles/secondary-schools-in-ireland-by-county', ]) seen = set() schools = [] while q: url = q.popleft() if url in seen: continue else: seen.add(url) # print(len(q)) parsed_url = urllib.parse.urlparse(url) for pattern, method in _URL_PREFIXES.items(): if parsed_url.path.lower().startswith(pattern): # print(parsed_url.path.lower()) content = fetch(url) method(content, q=q, schools=schools) print('\n\n\n\n\n') print(collections.Counter([x['ethos'] for x in schools if 'ethos' in x])) print(collections.Counter([x['type'] for x in schools if 'type' in x])) # print(collections.Counter([x.get('fee') for x in schools])) # print(collections.Counter([(x.get('type'), x.get('ethos')) for x in schools])) if __name__ == '__main__': run()