From 91a0843b2c917aaf07c745984df22867e3debb03 Mon Sep 17 00:00:00 2001 From: Ilia Miheev Date: Sat, 26 Apr 2025 16:59:51 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BA=D0=BE=D0=B4=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ipars/__init__.py | 1 + ipars/module.py | 88 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 ipars/__init__.py create mode 100644 ipars/module.py diff --git a/ipars/__init__.py b/ipars/__init__.py new file mode 100644 index 0000000..f7a72f0 --- /dev/null +++ b/ipars/__init__.py @@ -0,0 +1 @@ +from .module import Pars diff --git a/ipars/module.py b/ipars/module.py new file mode 100644 index 0000000..976c93c --- /dev/null +++ b/ipars/module.py @@ -0,0 +1,88 @@ +from selenium.webdriver.chrome.options import Options +from requests import get, RequestException +from selenium import webdriver +from time import sleep +from os import remove +from bs4 import BeautifulSoup + +class Pars: + '''Библиотека для работы с файлами во время парсинга''' + + def __init__(self, url, pathToSaveFile, writeMethod='w'): + """Конструктор""" + self.url = url + self.pathToSaveFile = pathToSaveFile + self.writeMethod = writeMethod + + def returnBs4Object(self, userEncoding='utf8'): + """Возвращаем объект beautifulsoup""" + with open(self.pathToSaveFile, encoding=userEncoding) as file: + src = file.read() + soup = BeautifulSoup(src, 'lxml') + return soup + + def deleteFile(self): + """Удаляем файл после работы с ним""" + remove(self.pathToSaveFile) + + + def get_static_page(self): + '''Получаем статическую страницу''' + headers = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36', + } + try: + # Отправляем запрос + req = get(self.url, headers=headers) + req.raise_for_status() # Проверка на ошибки HTTP + + # Записываем данные + if self.writeMethod == 'w': + src = req.text + with open(self.pathToSaveFile, self.writeMethod, encoding='utf-8') as file: + file.write(src) + elif self.writeMethod == 'wb': + src = req.content + with open(self.pathToSaveFile, self.writeMethod) as file: + file.write(src) + else: + raise ValueError("Неподдерживаемый метод записи: {}".format(self.writeMethod)) + + # Обрабатываем ошибки + except RequestException as e: + print(f"Ошибка при запросе: {e}") + except IOError as e: + print(f"Ошибка при записи в файл: {e}") + except Exception as e: + print('Ошибка:') + print(e) + + + def get_dinamic_page(self, closeWindow:bool=1): + '''Функция для получения динамической страницы''' + + + # Устанавливаем опции для Chrome WebDriver + options = Options() + if closeWindow: + options.add_argument('--headless') + # открываем браузер + with webdriver.Chrome(options=options) as driver: + driver.get(self.url) + # Прокручиваем страницу до самого низа + last_height = driver.execute_script("return document.body.scrollHeight") + while True: + # Прокручиваем до низа страницы + driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") + # Ждем загрузки страницы + sleep(2) + # Вычисляем новую высоту страницы + new_height = driver.execute_script("return document.body.scrollHeight") + if new_height == last_height: + break + last_height = new_height + # Получаем HTML-код страницы + html_content = driver.page_source + # Сохраняем HTML-код в файл + with open(self.pathToSaveFile, "w", encoding="utf-8") as file: + file.write(html_content) \ No newline at end of file