el1syum

Untitled

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