Необходимые библиотеки
import json
import re # библиотека для регулярных выражений
import requests # библиотека для запросов
from bs4 import BeautifulSoup # библиотека для парсинга
DOMAIN = 'https://www.herzen.spb.ru'
DOMAIN_ATLAS = 'https://atlas.herzen.spb.ru/'
RESULT = []
Поиск названия института в списке с https://www.herzen.spb.ru/main/structure/inst/
def search(inst):
for i in range(len(RESULT)):
if (RESULT[i])['inst_name'].lower().strip() == inst:
return i
Поиск управляющего на странице кафедры
def dep_html(url):
bs = BeautifulSoup(requests.get(url).text, 'html.parser')
table = bs.find_all(href=re.compile('teacher')) # все преподаватели
req = bs.find_all(class_='mm1')[2].string.split(', ')[0] # завкаф
for teacher in table:
teacher_name = teacher.string.strip()
if teacher_name == req:
return [teacher_name, teacher_html(DOMAIN_ATLAS + teacher['href'])]
Поиск почты на странице управляющего
def teacher_html(url):
bs = BeautifulSoup(requests.get(url).text, 'html.parser')
mail = bs.find_all(href=re.compile('mailto:'))[0].string
if mail is not None:
return mail
return 'Почта не найдена'
Парсинг всех институтов с главной страницы https://www.herzen.spb.ru/main/structure/inst/
bs = BeautifulSoup(requests.get('https://www.herzen.spb.ru/main/structure/inst/').text, 'html.parser')
inst_list = bs.find('td', {'class': 'blockwh'}).div.ul.contents
for item in inst_list:
print((item.string, DOMAIN + item.a['href']))
RESULT.append({'inst_name': item.string, 'url': DOMAIN + item.a['href'], 'dep_list': []})
print(RESULT)
Парсинг кафедр с атласа https://atlas.herzen.spb.ru/faculty.php
bs = BeautifulSoup(requests.get('https://atlas.herzen.spb.ru/faculty.php').text, 'html.parser')
dep_list = bs.find('td', {'class': 'body'}).div.ul.contents
for item in dep_list:
dep = []
inst_index = search(item.a.string.lower().strip())
if inst_index is not None:
for i in item.ul:
if i.string.lower().strip().startswith('кафедра'):
boss = dep_html(DOMAIN_ATLAS + i.a['href'])
if boss is not None: # проверка на существование завкаф
print({'dep_name': i.string.strip(), 'boss_name': boss[0], 'email': boss[1]})
dep.append({'dep_name': i.string.strip(), 'boss_name': boss[0], 'email': boss[1]})
RESULT[inst_index]['dep_list'] = dep
with open('parse.json', 'w') as f:
f.write(json.dumps(RESULT, ensure_ascii=False))