Repository navigation
Expand file tree
/
Copy pathне_актуальный_парсер.py
More file actions
113 lines (96 loc) · 4.67 KB
/
Copy pathне_актуальный_парсер.py
File metadata and controls
113 lines (96 loc) · 4.67 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
import requests
from bs4 import BeautifulSoup
import pandas
from pandas import ExcelWriter
import openpyxl
import lxml
"""
ДАННЫЙ ПАРСЕР НЕ АКТУАЛЕН, ОН НЕ РАБОТАЕТ. ССЫЛКА НА РАБОЧИЙ ПАРСЕР WILDBERRIES:
https://github.com/Timur1991/project_wildberries/blob/master/wildberries_parser_on_catalog.py
парсер торговой площадки Wildberries
приношу свои извинения, но В ДАННЫЙ МОМЕНТ ПАРСЕР НЕ РАБОТАЕТ (воспользуйтесь wildberries_parser_on_catalog.py)
По всем возникшим вопросам, можете писать в группу https://vk.com/happython
"""
def get_html(url, params=None):
"""html код страницы"""
headers = {
"Accept": "*/*",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0",
}
html = requests.get(url, headers=headers, params=params)
return html
def get_pages(html):
"""получение количества страниц"""
soup = BeautifulSoup(html.text, 'lxml')
try:
good_count = soup.find('span', class_='goods-count').get_text(strip=True).replace("\xa0", '')
pages = int(good_count) // 100 + 1
except:
pages = 1
return pages
def get_content(html):
"""сбор контента со страницы"""
soup = BeautifulSoup(html.text, 'html.parser')
items = soup.find_all('div', class_="product-card")
global title
title = soup.h1.text
cards = []
for item in items:
# проверка на наличии скидки, если нет, то поле пустое
try:
discount = item.find('span', class_='product-card__sale active')
if discount:
discount = discount.get_text(strip=True).replace('%', '')
else:
discount = item.find('span', class_='product-card__sale').get_text(strip=True).replace('%', '')
except:
discount = 0
# проверка цены
try:
price = item.find(class_='lower-price').get_text(strip=True).replace('\xa0', '').replace('₽', '')
except:
price = item.find('span', class_='price-commission__current-price').get_text(strip=True).replace('\xa0',
'').replace(
'₽', '')
cards.append({
'brand': item.find('strong', class_='brand-name').get_text(strip=True).replace('/', ''),
'title': item.find('span', class_='goods-name').get_text(),
'price': int(price),
'discount': int(discount),
'link': f'https://www.wildberries.ru{item.find("a", class_="product-card__main").get("href")}',
})
return cards
def save_exel(data, file_name):
"""сохранение собранных данных"""
dataframe = pandas.DataFrame(data)
writer = ExcelWriter(f'{file_name}.xlsx')
dataframe.to_excel(writer, 'data')
writer.save()
print(f'Данные сохранены в файл "{file_name}.xlsx"')
def parser(url):
"""основная функция"""
print(f'Парсим данные с: "{url}"')
html = get_html(url)
if html.status_code == 200:
pages = get_pages(html)
print(f'Количество страниц: {pages}')
cards = []
pages = int(input('Введите количество страниц: '))
for page in range(1, pages + 1):
print(f'Парсинг страницы: {page}')
html = get_html(url, params={'sort': 'popular', 'page': page})
cards.extend(get_content(html))
print(f'Всего: {len(cards)} позиций')
save_exel(cards, title)
else:
print(f'Ответ сервера:{html.status_code}. Парсинг невозможен!')
if __name__ == "__main__":
# parser('https://www.wildberries.ru/brands/xiaomi')
parser('https://www.wildberries.ru/brands/xiaomi/all')
"""Примеры ссылок:"""
# parser('https://www.wildberries.ru/catalog/sport/vidy-sporta/velosport/velosipedy')
# parser('https://www.wildberries.ru/catalog/knigi/uchebnaya-literatura?xsubject=2076')
# parser('https://www.wildberries.ru/catalog/knigi/uchebnaya-literatura?xsubject=3647')
# parser('https://www.wildberries.ru/brands/birkenstock')
"""Пример формата ссылки, с которым не работает парсер:"""
"https://www.wildberries.ru/catalog/0/search.aspx?search=%D0%BD%D0%BE%D1%83%D1%82%D0%B1%D1%83%D0%BA&xsearch=true"