Advertisement
Guest User

Untitled

a guest
Mar 16th, 2023
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.75 KB | None | 0 0
  1. from bs4 import BeautifulSoup as BS
  2. from openpyxl import Workbook, load_workbook
  3. from itertools import *
  4. from time import sleep
  5. import requests
  6. import asyncio
  7. import aiohttp
  8. from selenium import webdriver
  9. from selenium.webdriver.common.keys import Keys
  10.  
  11. def add_university_data(ws_universities, id_num, name, link, city):
  12.     ws_universities.append([id_num, name, link, city])
  13.  
  14.  
  15. def add_item_data(ws_items ,id_num, name, link):
  16.     ws_items.append([id_num, name, link])
  17.  
  18.  
  19. def add_directions_data(ws_directions, id_num, directions, num):
  20.     ws_directions.append([id_num, directions, num])
  21.  
  22. universities_data = []
  23. items_data = []
  24. direction_data = []
  25.  
  26.  
  27. async def get_page_data(session, page):
  28.     headers = {
  29.     "accept": 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  30.     'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
  31.     }
  32.     print(f'Страница №{page + 1} / 250')
  33.     url = f'https://www.ucheba.ru/for-abiturients/vuz/rossiya?s={page}0'
  34.  
  35.     async with session.get(url=url, headers=headers) as response:
  36.  
  37.         response_text = await response.text()
  38.  
  39.         # Основная страница
  40.         src = response_text.text
  41.         soup = BS(src, "lxml")
  42.         all_universiti_hrefs = soup.find_all('a', 'js_webstat')
  43.  
  44.         count_university = 1
  45.  
  46.         for link in all_universiti_hrefs:
  47.  
  48.             count_items = 0
  49.             count_derection = 0
  50.  
  51.             link_text = link.text
  52.             link_href = 'https://www.ucheba.ru' + link.get('href')
  53.  
  54.             response = session.get(url=link_href, headers=headers)
  55.             src = response.text
  56.  
  57.             soup = BS(src, 'lxml')
  58.             universities_citi = soup.find(
  59.                 'ul', 'params-list').find_all('li')[0].text.strip()
  60.  
  61.             universities_data.append(
  62.                 {
  63.                 count_university: [link_text, link_href, universities_citi]
  64.                 }
  65.             )
  66.  
  67.             response = session.get(url=link_href, headers=headers)
  68.             src = response.text
  69.  
  70.             soup = BS(src, 'lxml')
  71.  
  72.             receipt_group = soup.find('div', class_='ege-groups-list')
  73.  
  74.             try:
  75.                 for ul in receipt_group.find_all('div', class_='ege-groups-list__item'):
  76.                     items = []
  77.  
  78.                     for li in ul.find('ul', class_='ege-groups-list__subjects subjects-list').find_all('li'):
  79.                         items.append(li.text.replace(
  80.                             '\n', '').replace(' ', '-'))
  81.  
  82.                     items_name = '_'.join(items)
  83.  
  84.                     items_href = 'https://www.ucheba.ru' + ul.find('div', class_='ege-groups-list__info').find(
  85.                         'a', class_='ege-groups-list__programs-link').get('href')
  86.  
  87.                     items_data.append(
  88.                         {
  89.                         f'{count_university}_{count_items}': [items_name, items_href]
  90.                         }
  91.                     )
  92.  
  93.                     src = session.get(url=items_href, headers=headers)
  94.                     soup = BS(src.text, 'lxml')
  95.  
  96.                     if not soup.find('div', class_='paginator mt-25'):
  97.  
  98.                         all_derection = [i.text for i in soup.find_all(
  99.                             'a', class_='js_webstat')]
  100.                         all_passing_score = []
  101.                         for i in soup.find_all('div', class_='search-results-options'):
  102.                             if isinstance(i.text.split()[2]) or i.text.split()[2] == '—':
  103.                                 all_passing_score.append(i.text.split()[2])
  104.                             else:
  105.                                 all_passing_score.append(i.text.split()[3])
  106.  
  107.                         for d, p in zip_longest(all_derection, all_passing_score, fillvalue=' '):
  108.                             direction_data.append(
  109.                                 {
  110.                                 f'{count_university}_{count_items}_{count_derection}': [d, p]
  111.                                 }
  112.                             )
  113.                             count_derection += 1
  114.                     else:
  115.  
  116.                         page = soup.find(
  117.                             'div', class_='paginator mt-25').find_all('a')
  118.  
  119.                         for i in page:
  120.  
  121.                             items_href = items_href[:items_href[::-
  122.                                                                 1].page('//'[0])-1] + i.get('href')
  123.                             src = session.get(url=items_href, headers=headers)
  124.                             soup = BS(src.text, 'lxml')
  125.  
  126.                             all_derection = [j.text for j in soup.find_all(
  127.                                 'a', class_='js_webstat')]
  128.                             all_passing_score = []
  129.  
  130.                             for j in soup.find_all('div', class_='search-results-options'):
  131.  
  132.                                 if isinstance(j.text.split()[2]) or j.text.split()[2] == '—':
  133.                                     all_passing_score.append(j.text.split()[2])
  134.                                 else:
  135.                                     all_passing_score.append(j.text.split()[3])
  136.  
  137.                             for d, p in zip_longest(all_derection, all_passing_score, fillvalue=' '):
  138.                                 direction_data.append(
  139.                                     {
  140.                                     f'{count_university}_{count_items}_{count_derection}': [d, p]
  141.                                     }
  142.                                 )
  143.                                 count_derection += 1
  144.                         count_items += 1
  145.                        
  146.             except:
  147.                 print('Ошибка')
  148.                 continue
  149.  
  150.             count_university += 1
  151.     print(f'Обработана страница {page}')
  152.  
  153. #Без авторизации
  154. async def gather_data():
  155.     headers = {
  156.         "accept": 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  157.         'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
  158.     }
  159.  
  160.     async with aiohttp.ClientSession() as session:
  161.  
  162.         url = 'https://www.ucheba.ru/for-abiturients/vuz/rossiya'
  163.         response = await session.get(url = url, headers = headers)
  164.  
  165.         soup = BS(await response.text(), 'lxml')
  166.         pages_count = soup.find('div', 'paginator mt-25').find('ul').find_all('li')[-1].text
  167.  
  168.         tasks = []
  169.  
  170.         for page in range(0, pages_count + 1):
  171.             task = asyncio.create_task(get_page_data(session, page))
  172.             tasks.append(task)
  173.        
  174.         await asyncio.gether(*tasks)
  175.  
  176. '''#Авторизация добавлена, но не работает
  177. async def gather_data():
  178.    auth_data = {
  179.        "password": "Vi31128282",
  180.        "username": "brykovvita173@gmail.com",
  181.        "rememberMe": "true"
  182.    }
  183.    auth_url = 'https://api.ucheba.ru/v1/auth'
  184.  
  185.    headers = {
  186.        "accept": 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  187.        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
  188.    }
  189.  
  190.    async with aiohttp.ClientSession() as session:
  191.        # authorize first
  192.        await session.post(auth_url, data=auth_data, headers=headers)
  193.  
  194.        # get the initial page
  195.        url = 'https://www.ucheba.ru/for-abiturients/vuz/rossiya'
  196.        response = await session.get(url=url, headers=headers)
  197.  
  198.        soup = BS(await response.text(), 'lxml')
  199.        pages_count = soup.find('div', 'paginator mt-25').find('ul').find_all('li')[-1].text
  200.  
  201.        tasks = []
  202.  
  203.        for page in range(0, int(pages_count) + 1):
  204.            task = asyncio.create_task(get_page_data(session, page, headers))
  205.            tasks.append(task)
  206.        
  207.        await asyncio.gather(*tasks)
  208.  
  209.  
  210. async def get_page_data(session, page, headers):
  211.    url = f'https://www.ucheba.ru/for-abiturients/vuz/rossiya?page={page}'
  212.    response = await session.get(url=url, headers=headers)
  213. '''
  214.  
  215. def main():
  216.     asyncio.run(gather_data())
  217.  
  218.     wb = Workbook()
  219.     ws_universities = wb.active
  220.  
  221.     ws_universities.title = 'Universities'
  222.     ws_universities.append(
  223.         ['ID', 'Название вуза', 'Ссылка на страницу вуза', 'Город вуза'])
  224.  
  225.     ws_items = wb.create_sheet('Items')
  226.     ws_items.append(['ID', 'Предметы для поступления',
  227.                     'Ссылка на все направления по предметам'])
  228.  
  229.     ws_directions = wb.create_sheet('Directions')
  230.     ws_directions.append(['ID', 'Направления', 'Минимальный балл'])
  231.  
  232.     wb.save(
  233.             f'/home/kukuruzka-vitya/CODE/za_python/parsing/pars_university_first/university.xlsx')
  234.  
  235.     for data_un in universities_data:
  236.         for university_num, items in data_un.items():
  237.             add_university_data(ws_universities, university_num, items[0], items[1], items[2])
  238.  
  239.     for data_un in items_data:
  240.         for university_num, items in data_un.items():
  241.             add_university_data(ws_items ,university_num.split('_')[0], items[0], items[1])
  242.  
  243.     for data_un in direction_data:
  244.         for university_num, items in data_un.items():
  245.             add_university_data(ws_directions ,university_num.split('_')[0], items[0], items[1])
  246.    
  247.     wb.save(
  248.         f'/home/kukuruzka-vitya/CODE/za_python/parsing/pars_university_first/university.xlsx')
  249.  
  250. if __name__ == '__main__':
  251.     main()
  252.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement