Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import requests

from bs4 import BeautifulSoup


import json

def get_iphone_models(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

iphone_models = []

# Цикл для отримання даних про кожен товар на сторінці


products = soup.find_all('div', class_='goods-tile__inner')
for product in products:
model = {}
model['Назва'] = product.find('span', class_='goods-
tile__title').text.strip()
model['Ціна'] = product.find('span', class_='goods-tile__price-
value').text.strip()

# Кольори
colors_list = []
colors_elem = product.find('ul', class_='goods-tile__colors-list')
if colors_elem:
color_items = colors_elem.find_all('li', class_='goods-tile__colors-
item')
for color_item in color_items:
style = color_item.find('span', class_='goods-tile__colors-
content')['style']
color = style.split(':')[-1].strip(';').strip()
colors_list.append(color)
else:
colors_list = ['Не вказано']

model['Колір'] = colors_list

# Переходимо на окрему сторінку моделі для отримання інших характеристик


product_link = product.find('a', class_='goods-tile__picture').get('href')
model_page_response = requests.get(product_link)
model_page_soup = BeautifulSoup(model_page_response.content, 'html.parser')

# Знаходимо інші характеристики екрана на сторінці моделі


screen_details = {}
for detail in ['Роздільна здатність дисплея', 'Тип матриці', 'Серія']:
detail_elem = model_page_soup.find('dt', string=detail)
if detail_elem:
screen_details[detail] = detail_elem.find_next('dd').text.strip()
else:
screen_details[detail] = 'Не вказано'

model.update(screen_details)

iphone_models.append(model)
return iphone_models

def save_to_json(data):
with open('iphone_models.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
if __name__ == "__main__":
url = 'https://rozetka.com.ua/ua/mobile-phones/c80003/producer=apple/'
iphone_models = get_iphone_models(url)
save_to_json(iphone_models)

You might also like