schooldays_crawler.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import collections
  2. import sys
  3. import hashlib
  4. import queue
  5. import os
  6. import urllib.parse
  7. import re
  8. import requests
  9. import bs4
  10. _WEB_CACHE_DIR = '.web-cache'
  11. def _extract_secondary_progression(content):
  12. doc = bs4.BeautifulSoup(content, 'html.parser')
  13. table = doc.find(id='sch1')
  14. print(table.text)
  15. def _process_school(content, schools, **_):
  16. doc = bs4.BeautifulSoup(content, 'html.parser')
  17. data = {
  18. 'name': doc.find(id='area1').h1.get_text().strip()
  19. }
  20. for link in doc.find_all('a'):
  21. url = link.get('href')
  22. if url.startswith('https://www.google.com/maps/search/?'):
  23. parsed = urllib.parse.urlparse(link.get('href'))
  24. params = urllib.parse.parse_qs(parsed.query)
  25. if 'query' in params:
  26. latlon = params['query'][0].split(',')
  27. data['lat'] = float(latlon[0].strip())
  28. data['lon'] = float(latlon[1].strip())
  29. elif url.endswith('/college-progression'):
  30. content = fetch(url)
  31. data['progression'] = _extract_secondary_progression(content)
  32. # print(doc.area1)
  33. a1 = doc.find(id='area1').get_text()
  34. for line in a1.splitlines():
  35. if line.startswith('Primary School'):
  36. data['type'] = 'primary'
  37. elif line.startswith('Secondary School'):
  38. data['type'] = 'secondary'
  39. elif line.startswith('Post Primary School'):
  40. data['type'] = 'secondary'
  41. elif line.startswith('Ethos: '):
  42. ethos = line[7:].split(',')[0].strip(' \xa0')
  43. ethos = ethos.lower()
  44. ethos = ethos.replace('-', '').replace('inter','multi')
  45. if '\xa0' in ethos:
  46. ethos = ethos.split('\xa0')[0].strip()
  47. if ethos and ethos not in ['other/unknown']:
  48. data['ethos'] = ethos
  49. elif line.startswith('Fees: Yes '):
  50. try:
  51. data['fee'] = int(line[11:].replace(',','').replace(' per year',''))
  52. except ValueError:
  53. data['fee'] = line[11:].replace(',','').replace(' per year','')
  54. schools.append(data)
  55. def _process_index(content, q, **_):
  56. doc = bs4.BeautifulSoup(content, 'html.parser')
  57. for link in doc.find_all('a'):
  58. url = link.get('href').lower()
  59. q.append(url)
  60. _URL_PREFIXES = {
  61. '/articles/primary-schools-in-ireland-by-county': _process_index,
  62. # '/primary-schools-in-ireland': _process_index,
  63. '/primary-schools-in-ireland/primary-dublin': _process_index,
  64. '/articles/secondary-schools-in-ireland-by-county': _process_index,
  65. # '/secondary-schools-in-ireland': _process_index,
  66. '/secondary-schools-in-ireland/dublin': _process_index,
  67. '/school/': _process_school,
  68. }
  69. def fetch(url):
  70. if not os.path.isdir(_WEB_CACHE_DIR):
  71. os.mkdir(_WEB_CACHE_DIR)
  72. if url.startswith('/'):
  73. url = 'https://www.schooldays.ie' + url
  74. fname = os.path.join(_WEB_CACHE_DIR, hashlib.md5(url.encode('utf-8')).hexdigest())
  75. print((url, fname))
  76. if os.path.isfile(fname):
  77. with open(fname) as f:
  78. return f.read()
  79. resp = requests.get(url, timeout=20)
  80. if resp.status_code == 200:
  81. with open(fname, 'wb') as f:
  82. f.write(resp.content)
  83. return resp.content
  84. else:
  85. raise Exception('%i: %s' % (resp.status_code, url))
  86. def run():
  87. q = None
  88. if len(sys.argv) > 1:
  89. q = queue.deque(sys.argv[1:])
  90. else:
  91. q = queue.deque([
  92. 'https://www.schooldays.ie/articles/primary-schools-in-ireland-by-county',
  93. 'https://www.schooldays.ie/articles/secondary-schools-in-ireland-by-county',
  94. ])
  95. seen = set()
  96. schools = []
  97. while q:
  98. url = q.popleft()
  99. if url in seen:
  100. continue
  101. else:
  102. seen.add(url)
  103. # print(len(q))
  104. parsed_url = urllib.parse.urlparse(url)
  105. for pattern, method in _URL_PREFIXES.items():
  106. if parsed_url.path.lower().startswith(pattern):
  107. # print(parsed_url.path.lower())
  108. content = fetch(url)
  109. method(content, q=q, schools=schools)
  110. print('\n\n\n\n\n')
  111. print(collections.Counter([x['ethos'] for x in schools if 'ethos' in x]))
  112. print(collections.Counter([x['type'] for x in schools if 'type' in x]))
  113. # print(collections.Counter([x.get('fee') for x in schools]))
  114. # print(collections.Counter([(x.get('type'), x.get('ethos')) for x in schools]))
  115. if __name__ == '__main__':
  116. run()