el1syum

Untitled

Aug 17th, 2023
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. import time
  2. from time import sleep
  3.  
  4. import requests
  5. from bs4 import BeautifulSoup
  6. from openpyxl import Workbook
  7.  
  8.  
  9. # Функция для парсинга страницы и сохранения данных в Excel
  10. def parse_page(next_response, ws):
  11.     soup = BeautifulSoup(next_response.content, 'html.parser')
  12.     table = soup.find('table')
  13.  
  14.     rows = table.findAll('tr')
  15.  
  16.     for row in rows:
  17.         cells = row.findAll('td')
  18.         data = []
  19.         for cell in cells:
  20.             data.append(cell.text.strip())
  21.         ws.append(data)
  22.  
  23.  
  24. def main():
  25.     session = requests.Session()
  26.  
  27.     # Создаем объект Workbook для создания Excel файла
  28.     wb = Workbook()
  29.     # Активируем лист
  30.     ws = wb.active
  31.  
  32.     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'
  33.     response = session.get(url)
  34.     soup = BeautifulSoup(response.content, 'html.parser')
  35.     parse_page(response, ws)
  36.  
  37.     ccc = 0
  38.     # Парсинг остальных страниц с помощью кнопки "вперед"
  39.     while ccc <= 10000:
  40.         next_button = soup.find('a', string='Вперед →')
  41.         if next_button:
  42.             next_page_url = next_button['href']
  43.             next_response = session.get(next_page_url)
  44.             soup = BeautifulSoup(next_response.content, 'html.parser')
  45.             if next_response.status_code != 200:
  46.                 print(f'\n{next_response.url} - {next_response.status_code}\n')
  47.                 time.sleep(1)
  48.                 continue
  49.  
  50.             sleep(0.6)
  51.             parse_page(next_response, ws)
  52.             ccc += 1
  53.             print(ccc)
  54.         else:
  55.             break
  56.  
  57.     # Сохраняем Excel файл
  58.     wb.save('output.xlsx')
  59.  
  60.  
  61. if __name__ == '__main__':
  62.     main()
  63.  
Advertisement
Add Comment
Please, Sign In to add comment