el1syum

Untitled

Aug 25th, 2023 (edited)
1,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.52 KB | None | 0 0
  1. from time import sleep
  2. import requests
  3. from bs4 import BeautifulSoup
  4. from openpyxl import Workbook
  5.  
  6.  
  7. def get_name(row):
  8.     url = ''.join(map(lambda i: i.get('href'), row.find_all('a')))
  9.     r = requests.get(url)
  10.     soup = BeautifulSoup(r.text, 'html.parser')
  11.     try:
  12.         name = soup.find('div', string='Наименование').find_next('div').text.strip()
  13.     except AttributeError:
  14.         name = ''
  15.         print(f'no name {r.url}')
  16.     return name
  17.  
  18.  
  19. # Функция для парсинга страницы и сохранения данных в Excel
  20. def parse_page(next_response, ws):
  21.     soup = BeautifulSoup(next_response.content, 'html.parser')
  22.     table = soup.find('table').find('tbody')
  23.  
  24.     rows = table.findAll('tr')
  25.  
  26.     for row in rows:
  27.         name = get_name(row)
  28.         cells = row.findAll('td')
  29.         data = []
  30.         for cell in cells:
  31.             data.append(cell.text.strip())
  32.         data.append(name)
  33.         ws.append(data)
  34.  
  35.  
  36. def main():
  37.     session = requests.Session()
  38.  
  39.     # Создаем объект Workbook для создания Excel файла
  40.     wb = Workbook()
  41.     # Активируем лист
  42.     ws = wb.active
  43.  
  44.     url = 'https://www.rst.gov.ru/portal/gost/home/activity/compliance/evaluationcompliance/AcknowledgementCorrespondence/safetycertificate018?portal:componentId=ff119059-8bd4-47fc-95f6-a70de17a4b3e&portal:isSecure=false&portal:portletMode=view&navigationalstate=JBPNS_rO0ABXdgAAhwYWdlU2l6ZQAAAAEAAjIwAAdvcmRlckJ5AAAAAQAYZGF0ZW9maXNzdWVvZmNlcnRpZmljYXRlAARmcm9tAAAAAQABMAAFb3JkZXIAAAABAARERVNDAAdfX0VPRl9f'
  45.     response = session.get(url)
  46.     soup = BeautifulSoup(response.content, 'html.parser')
  47.     parse_page(response, ws)
  48.  
  49.     ccc = 0
  50.     # Парсинг остальных страниц с помощью кнопки "вперед"
  51.     while ccc <= 2:
  52.         next_button = soup.find('a', string='Вперед →')
  53.         if next_button:
  54.             next_page_url = next_button['href']
  55.             next_response = session.get(next_page_url)
  56.  
  57.             sleep(0.6)
  58.             try:
  59.                 parse_page(next_response, ws)
  60.             except Exception as e:
  61.                 print(f'{next_response.url} - {next_response.status_code}\n{e}')
  62.                 continue
  63.             soup = BeautifulSoup(next_response.content, 'html.parser')
  64.  
  65.             ccc += 1
  66.             print(ccc)
  67.         else:
  68.             break
  69.  
  70.     # Сохраняем Excel файл
  71.     wb.save('output.xlsx')
  72.  
  73.  
  74. if __name__ == '__main__':
  75.     main()
  76.  
Advertisement
Add Comment
Please, Sign In to add comment