el1syum

Untitled

Aug 19th, 2022
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.75 KB | None | 0 0
  1. import logging
  2. import os
  3.  
  4. import openpyxl
  5. import requests
  6. from tqdm import tqdm
  7.  
  8.  
  9. def get_data():
  10.     logging.basicConfig(
  11.         level=logging.INFO
  12.     )
  13.     if not os.path.exists('images'):
  14.         os.mkdir('images')
  15.     book = openpyxl.Workbook()
  16.     for sheet in book.worksheets:
  17.         sheet.append(['Название', 'Описание', 'Идентификатор', 'Учредитель', 'Сокращенное название',
  18.                       'Тип собственности', 'КОПУК', 'Тип по профилю', 'ОГРН', 'ИНН', 'Юр. адрес',
  19.                       'Фактическое нахождение', 'Телефон', 'Email', 'Сайт', 'Руководитель', 'ОКПО',
  20.                       'Путь до фотографий'])
  21.     headers = {
  22.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0',
  23.         'Accept': 'application/json, text/plain, */*',
  24.         'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
  25.         'Connection': 'keep-alive',
  26.         'Referer': 'https://goskatalog.ru/portal/',
  27.         'Sec-Fetch-Dest': 'empty',
  28.         'Sec-Fetch-Mode': 'cors',
  29.         'Sec-Fetch-Site': 'same-origin',
  30.     }
  31.     params = {
  32.         'cacheEnabled': 'true',
  33.         'limit': '20000',
  34.         'offset': '0',
  35.         'publicationLimit': 'false',
  36.     }
  37.     r = requests.get('https://goskatalog.ru/muzfo-rest/rest/museums', params=params, headers=headers)
  38.     data = r.json()
  39.     museums = data.get('museums')
  40.     for museum in tqdm(museums[:100]):
  41.         try:
  42.             inn = okpo = ogrn = address = mail = number = website = actual_address = headmaster = own_type = '-'
  43.             i = 1
  44.             id = museum.get('id')
  45.             url = f'https://goskatalog.ru/muzfo-rest/rest/museums/{id}'
  46.             r = requests.get(url, headers=headers)
  47.             data = r.json()
  48.             title = data.get('name')  # название
  49.             abbreviation = data.get('abbreviation')  # сокращенное название
  50.             annotation = data.get('annotation')  # описание
  51.             if annotation == None:
  52.                 annotation = '-'
  53.             else:
  54.                 annotation = annotation.replace('\n', '').replace('\r', '').replace('\t', '').strip()
  55.             founder = data.get('founder')  # основатель
  56.             kopuk = data.get('code')  # копук
  57.             unic_identifier = data.get('fullUin')  # уникальный идентификатор
  58.             # with open('data2.json', 'w', encoding='utf-8') as file:
  59.             #     json.dump(data, file, indent=4, ensure_ascii=False)
  60.  
  61.             identifiers = data.get('identifiers')
  62.             for identifier in identifiers:
  63.                 name = identifier.get('type')
  64.                 value = identifier.get('value')
  65.                 if name == 'INN':
  66.                     inn = value  # инн
  67.                 elif name == 'OKPO':
  68.                     okpo = value  # окпо
  69.                 elif name == 'OGRN':
  70.                     ogrn = value  # огрн
  71.  
  72.             contacts = data.get('contacts')
  73.             for contact in contacts:
  74.                 value = contact.get('contactValue')
  75.                 if '@' in value:
  76.                     mail = value
  77.                 elif '+7' in value:
  78.                     number = value
  79.                 elif 'http' in value:
  80.                     website = value
  81.                 elif 'ул' in value or 'д' in value:
  82.                     if address != '-':
  83.                         if value != address:
  84.                             actual_address = value
  85.                             continue
  86.                     address = value
  87.  
  88.             if actual_address == '-':
  89.                 actual_address = address
  90.  
  91.             images = data.get('images')
  92.  
  93.             file_title = title.replace('\\', '.') \
  94.                              .replace('"', '').replace('|', '').replace('*', 'x').replace(':', '') \
  95.                              .replace('?', '.').replace('<', '').replace('>', '').replace('/', '.') \
  96.                              .replace('\n', '')[:200]
  97.             for image in images:
  98.                 code = image.get('code')
  99.                 id = image.get('id')
  100.                 image_url = f'https://goskatalog.ru/muzfo-imaginator/rest/images/public/350/{code}/{id}.jpg'
  101.                 r = requests.get(image_url)
  102.                 with open(f'images/{file_title}_{i}.jpg', 'wb') as file:
  103.                     file.write(r.content)
  104.                 i += 1
  105.  
  106.             profile_type = data.get('types')[0].get('name')  # тип по профилю
  107.  
  108.             employees = data.get('employees')
  109.             for employee in employees:
  110.                 if employee.get('roleId') == 1:
  111.                     headmaster = employee.get('name')  # руководитель
  112.  
  113.             ownershipid = data.get('ownershipId')
  114.             if ownershipid == 3:
  115.                 own_type = 'Муниципальная'
  116.             elif ownershipid == 2:
  117.                 own_type = 'Субъекта РФ'
  118.             elif ownershipid == 1:
  119.                 own_type = 'Федеральная'
  120.  
  121.             if annotation != '-':
  122.                 logging.info(annotation + '\n')
  123.  
  124.             for sheet in book.worksheets:
  125.                 sheet.append([title, annotation, unic_identifier, founder, abbreviation,
  126.                               own_type, kopuk, profile_type, ogrn, inn, address,
  127.                               actual_address, number, mail, website, headmaster, okpo, f'images/{file_title}'])
  128.         except Exception as e:
  129.             print(e)
  130.         finally:
  131.             book.save('data.xlsx')
  132.  
  133.  
  134. def main():
  135.     get_data()
  136.  
  137.  
  138. if __name__ == '__main__':
  139.     main()
  140.  
Advertisement
Add Comment
Please, Sign In to add comment