-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheksmo_parser.py
More file actions
133 lines (107 loc) · 5.41 KB
/
Copy patheksmo_parser.py
File metadata and controls
133 lines (107 loc) · 5.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# -*- coding: utf-8 -*-
"""eksmo_parser
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1EPqEAUvNW6-2ecYQ7V-TgvpEYxyPfQ1U
"""
from tqdm import tqdm # Для прогресс-бара
import logging
import requests
from time import sleep
from bs4 import BeautifulSoup
import random
import numpy as np
import pandas as pd
# Настройка логирования
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Базовый URL
base_url = 'https://eksmo.ru'
# Жанры для парсинга
genres = ['khudozhestvennaya-literatura', 'nekhudozhestvennaya-literatura', 'dom-dosug-rukodelie', 'kulinariya', 'biznes-literatura',
'deti-i-roditeli', 'knigi-dlya-roditeley', 'vse-dlya-shkoly-i-postupleniya', 'knigi-dlya-podrostkov', 'comics_adult',
'knigi-o-rossii', 'puteshestviya', 'professionalnaia-literatura', 'inostrannye-yaziki', 'erotika-sex']
books = []
# Функция для подключения к странице
def connect(url):
try:
response = requests.get(url)
response.raise_for_status() # Проверка на ошибки HTTP
logging.info(f"Успешно подключено к: {url}")
return response
except requests.exceptions.RequestException as e:
logging.error(f"Ошибка подключения к {url}: {e}")
return None
# Функция, которая достает все интересующие нас поля по конкретной книге
def GetBookData(url0):
page0 = requests.get(url0)
page0.encoding = 'utf-8'
soup0 = BeautifulSoup(page0.text, 'html')
try:
author = soup0.find_all('meta', {'name' : 'mailfit-product-author'})[0].get('content')
except IndexError:
author = None
title = soup0.find_all('meta', {'name' : 'mailfit-product-name'})[0].get('content')
price = soup0.find_all('meta', {'name' : 'mailfit-product-price'})[0].get('content')
description = soup0.find_all('meta', {'itemprop' : 'description'})[0].get('content')[3:-4]
brand = soup0.find_all('meta', {'itemprop' : 'brand'})[0].get('content')
isbn = soup0.find_all('meta', {'itemprop' : 'gtin8'})[0].get('content')[5:]
category = soup0.find_all('a', {'class': 'breadcrumbs__link'})[2].text
genre = soup0.find_all('a', {'class': 'breadcrumbs__link'})[3].text
props = soup0.find_all('div', {'class': 'book-page__card-prop'})
release_date = next((prop.text.replace(' Дата выхода: ', '').strip() for prop in props if 'Дата выхода:' in prop.text), None)
age_limit = next((prop.text.replace(' Возрастное ограничение: ', '').strip() for prop in props if 'Возрастное ограничение:' in prop.text), None)
pages_count = next((prop.text.replace(' Кол-во страниц: ', '').strip() for prop in props if 'Кол-во страниц:' in prop.text), None)
reading_time = next((prop.text.replace(' Время прочтения: ', '').strip() for prop in props if 'Время прочтения:' in prop.text), None)
books.append({
'author': author,
'title': title,
'price': price,
'description': description,
'brand': brand,
'ISBN': isbn,
'category': category,
'genre': genre,
'release_date': release_date,
'age_limit': age_limit,
'pages_count': pages_count,
'reading_time': reading_time
})
# Функция для парсинга страницы
def parse_page(url):
try:
response = connect(url)
if response:
logging.info(f"Парсинг страницы: {url}")
page = requests.get(url)
page.encoding = 'utf-8'
soup = BeautifulSoup(page.text, 'html')
urls = []
for link in soup.find_all('a', href=True):
href = link['href']
if href.startswith('/book/') and 'ITD' in link.get('href'): # фильтруем только ссылки на книги
full_url = 'https://eksmo.ru' + href # добавляем домен, потому что изначально его нет...
urls.append(full_url)
urls = list(set(urls))
for link in urls:
GetBookData(link)
sleep(3)
except Exception as e:
logging.error(f"Ошибка при парсинге страницы {url}: {e}")
# Основная функция
def main():
for genre in tqdm(genres, desc="Обработка жанров"): # Прогресс-бар для жанров
genre_link = f'{base_url}/{genre}'
logging.info(f"Обработка жанра: {genre}")
# Подключение к странице жанра
if not connect(genre_link):
continue # Переход к следующему жанру, если текущий недоступен
# Парсинг страниц жанра
for i in tqdm(range(1, 100), desc=f"Парсинг страниц жанра {genre}", leave=False):
page_link = f'{genre_link}/page{i}'
parse_page(page_link)
if __name__ == "__main__":
main()
df = pd.DataFrame(books)
df.columns = ['author', 'title', 'price (rub)', 'description', 'brand', 'ISBN',
'category', 'genre', 'release_date', 'age_limit', 'pages_count', 'reading_time']
df.to_csv('eksmo.csv', index=False)