-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
103 lines (78 loc) · 2.76 KB
/
main.py
File metadata and controls
103 lines (78 loc) · 2.76 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
import requests
from bs4 import BeautifulSoup, ResultSet, Tag
from model import Product
import json
import csv
def parser(url: str, max_item: int):
create_json()
create_csv()
page: int = 1
count_items: int = 0
while max_item > count_items:
products: list[Product] = []
res = requests.get(url=f'{url}&p={page}')
soup = BeautifulSoup(res.text, 'lxml')
product_cards: ResultSet = soup.find_all('div', class_='product-card')
for product in product_cards:
if count_items >= max_item:
break
count_items += 1
name: str = product.get('data-product-name')
sku: str = product.find('span', class_='product-card__key').text
pre_link_element: Tag = product.find('meta', itemprop='name')
link: str = (pre_link_element
.findNext()
.get('href'))
price_tag: Tag = product.find('span', itemprop='price')
if price_tag:
price: str = price_tag.get('content')
else:
price: str = 'По запросу'
print(f'{count_items}-й товар\n' # Для отладки
f'Название: {name}\n'
f'Код: {sku}\n'
f'Ссылка на товар: {link}\n'
f'Цена за штуку: {price}\n')
products.append(Product(
sku=sku,
name=name,
link=link,
price=price
))
write_json(products)
write_csv(products)
page += 1
def create_json():
open(file=f'glavsnab.json', mode='w', newline='')
def write_json(products: list[Product]):
data: dict = {'product': []}
for product in products:
data['product'].append({
'sku': product.sku,
'name': product.name,
'link': product.link,
'price': product.price
})
with open(file=f'glavsnab.json', mode='a', newline='') as file:
json.dump(obj=data, fp=file)
def create_csv():
with open(file=f'glavsnab.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow([
'sku',
'name',
'link',
'price'
])
def write_csv(products: list[Product]):
with open(file=f'glavsnab.csv', mode='a', newline='') as file:
writer = csv.writer(file)
for product in products:
writer.writerow([
product.sku,
product.name,
product.link,
product.price
])
if __name__ == '__main__':
parser(url='https://glavsnab.net/zimniye-tovary.html?limit=100', max_item=672)