import requests
import json
import sys
sys.path.insert(0,’bs4.zip’)
from bs4 import BeautifulSoup
Imitate the Mozilla browser.
user_agent = {‘User-agent’: ‘Mozilla/5.0’}
def compare_prices(laughs_coconut_url, glomark_coconut_url):
#TODO: Aquire the web pages which contain product Price
laughs_response = requests.get(laughs_coconut_url, headers=user_agent)
glomark_response = requests.get(glomark_coconut_url, headers=user_agent)
#TODO: LaughsSuper supermarket website provides the price in a span text.
soup_laughs = BeautifulSoup(laughs_response.text, 'html.parser')
price_laughs = soup_laughs.findAll('span', {'class': 'price'})[1].text.replace("Rs.", "").strip()
product_name_laughs = soup_laughs.find('h1').text.strip() if soup_laughs.find('h1') else "Unknown Product"
#TODO: Glomark supermarket website provides the data in jason format in an inline script.
#You can use the json module to extract only the price
soup_glomark = BeautifulSoup(glomark_response.text, 'html.parser')
data_glomark = json.loads(soup_glomark.find('script', {'type': 'application/ld+json'}).text)
price_glomark = float(data_glomark['offers'][0]['price'])
product_name_glomark = data_glomark['name']
#TODO: Parse the values as floats, and print them
price_laughs = float(price_laughs)
print(f'Laughs {product_name_laughs} Rs.: {price_laughs}')
print(f'Glomark {product_name_glomark} Rs.: {price_glomark}')
if price_laughs > price_glomark:
print(f'Glomark is cheaper by Rs.: {price_laughs - price_glomark}')
elif price_laughs < price_glomark:
print(f'Laughs is cheaper by Rs.: {price_glomark - price_laughs}')
else:
print('Prices are the same')
URLs to compare
laughs_coconut_url = ‘https://scrape-sm1.github.io/site1/COCONUT%20market1super.html’
glomark_coconut_url = ‘https://glomark.lk/coconut/p/11624’
compare_prices(laughs_coconut_url, glomark_coconut_url)
i got thisTime limit exceeded
Prabod Chamika Rajapaksha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.