Есть два интернет-супермаркета, которые предоставляют цены на различные продукты.
Вам нужно написать программу для получения, извлечения и сравнения цен на данный продукт у этих двух поставщиков.
Пример: Цену на кокос от двух разных поставщиков можно найти на следующих веб-страницах.
laughs_coconut = 'https://scrape-sm1.github.io/site1/COCO ... super.html'
glomark_coconut = 'https://glomark.lk/coconut/p/11624'
Функция def Compare_prices(product_laughs,product_glomark) возьмет два похожих товары от двух поставщиков и сравните цены, чтобы порекомендовать вам, какой вариант дешевле в данный момент времени.
1. Посетите ссылки в своем веб-браузере и используйте инструменты браузера «Проверить элементы» / «Просмотр исходного кода страницы», чтобы понять структуру веб-страниц, приведенных выше.
2. Выполните функцию Compare_prices, которая предварительно загружена в поле ответа, чтобы получить и извлечь значения цен с двух веб-страниц.
Пример ожидаемого результата
Код: Выделить всё
Laughs COCONUT - Item#mr-2058 Rs.: 89.0
Glomark Coconut Rs.: 86.0
Glomark is cheaper: 3.0
Код: Выделить всё
import requests
import json
import re
import sys
sys.path.insert(0,'bs4.zip')
from bs4 import BeautifulSoup
#Imitate the Mozilla browser.
user_agent = {'User-agent': 'Mozilla/5.0'}
# ---------------- Helper Function ----------------
def compare_prices(product_laughs, product_glomark):
# ---------------- LaughsSuper ----------------
resp_laughs = requests.get(product_laughs, headers=user_agent)
soup_laughs = BeautifulSoup(resp_laughs.text, 'html.parser')
product_name_laughs = soup_laughs.find('h1').text.strip()
# Try span.price first
price_tag = soup_laughs.find('span', class_='price')
if price_tag is None:
# If not found, try div.product-price
price_tag = soup_laughs.find('div', class_='product-price')
# Safely extract text and convert to float
price_text = price_tag.get_text()
price_laughs = float(re.search(r'\d+(\.\d+)?', price_text).group())
# ---------------- Glomark ----------------
resp_glomark = requests.get(product_glomark, headers=user_agent)
soup_glomark = BeautifulSoup(resp_glomark.text, 'html.parser')
script_tag = soup_glomark.find('script', type='application/ld+json')
data = json.loads(script_tag.string)
if isinstance(data, list):
data = data[0]
offers = data['offers']
if isinstance(offers, list):
offers = offers[0]
product_name_glomark = data['name']
price_glomark = float(offers['price'])
print('Laughs ', product_name_laughs, 'Rs.: ', price_laughs)
print('Glomark ', product_name_glomark, 'Rs.: ', price_glomark)
if price_laughs > price_glomark:
print('Glomark is cheaper Rs.:', price_laughs - price_glomark)
elif price_laughs < price_glomark:
print('Laughs is cheaper Rs.:', price_glomark - price_laughs)
else:
print('Price is the same')
Ожидается
Код: Выделить всё
Laughs COCONUT - Item#mr-2058 Rs.: 95.0
Glomark COCONUT Rs.: 172.0
Laughs is cheaper Rs.: 77.0
Код: Выделить всё
Laughs COCONUT - Item#mr-2058 Rs.: 0.0
Glomark COCONUT Rs.: 172.0
Laughs is cheaper Rs.: 172.0
Код: Выделить всё
Laughs COCA COLA 2L (PET) - Item#mr-35457 Rs.: 270.0
Glomark Coca-Cola Pet 2L Rs.: 500.0
Laughs is cheaper Rs.: 230.0
Код: Выделить всё
Laughs COCA COLA 2L (PET) - Item#mr-35457 Rs.: 0.0
Glomark Coca-Cola Pet 2L Rs.: 500.0
Laughs is cheaper Rs.: 500.0
Подробнее здесь: https://stackoverflow.com/questions/798 ... lsoup-json
Мобильная версия