Build Daily Price Tracker on Decathlon in Python: Web Scraping, Email Automation & Scheduling in 4 steps

python

Python Automation can play an important role if you know how to leverage it. In today’s e-commerce-driven world, online shopping has become a routine part of life. However, finding the best deals or price drops on your favorite products can be a bit of a hassle. Wouldn’t it be great if you could get an alert whenever your desired product hits a target price? Well, you can! In this blog, we’ll create a simple Decathlon Price Tracker using Python, web scraping, and email notifications. This is a perfect introductory project for those looking to break into Data Science and Python programming.

Through this project, you’ll learn how to automate data collection, analyze product prices, and send email alerts when prices drop below a certain threshold. Whether you are a beginner or someone looking to build practical projects, this will provide you with hands-on experience in Python. By the end of this post, you’ll have a functioning price tracker and, a deeper understanding of data science principles.

Overview of this Python Project

In this Python project, we are going to create a code that will scrape the price of a particular product and check whether the price has dropped as per my conditioning and if it happens an email must be sent to me notifying me about the price drop.

Let’s understand the code step by step

  1. Importing Required Libraries of Python:
import requests                  # It allows you to send http requests and retrieve web content.
from bs4 import BeautifulSoup    # Library for webscraping and access a particular data.
import smtplib                   # Library to send emails
from email.mime.multipart import MIMEMultipart  # Module to form the structure of a mail.
from email.mime.text import MIMEText            
JavaScript

requests: This library helps us send HTTP requests and retrieve web content.
BeautifulSoup: A powerful library for web scraping, used to parse the HTML content and extract specific data points (in our case, the product price).
smtplib: A built-in library in Python for sending emails using the SMTP protocol.
MIMEMultipart and MIMEText: These are used to create and send rich-format email messages (with a subject line, body text, etc.).

Recommendation: To understand How Email Automation in Python works watch this

2. Define the Function to Check the Price:

def check_price(url, target_price, email):
    try:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, 'html.parser')

        
        price = soup.find('span', {'class': 'text-26 mr-4 font-bold text-black'}).get_text()
        price = price.replace('', '').replace(',', '').replace('', '').strip()
        price = float(price)

        print(f"Current price: ₹{price}")

        if price <= target_price:
            print(f"Price drop detected: ${price}! Sending email to {email}.")
            send_email(email, url, price)
        else:
            print(f"No price drop detected. The current price is still ₹{price}. Target price is ₹₹{target_price}.")

    except Exception as e:
        print(f"Error occurred while checking the price: {e}")
JavaScript

This function has 3 parameters that are URL, target_price, and email. In this function, we have used exception-handling, which will check first if the scraping of price from a particular URL (page) using requests and the bs4 library is possible. If this is the case we will find the price of the product and an email will trigger by calling the sendmail function otherwise an error will be generated and except will handle it.

python

3. Defint the function to send the mail:

def send_email(to_email, product_url, price):
    from_email = "youremail"
    from_password = "yourpassword"

    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = f"Price Drop Alert: ₹{price}"

    body = f"The price of the product has dropped to ${price}. Check it out here: {product_url}"
    msg.attach(MIMEText(body, 'plain'))

    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(from_email, from_password)
        text = msg.as_string()
        server.sendmail(from_email, to_email, text)
        server.quit()
        print(f"Email sent successfully to {to_email} about the price drop.")
    except Exception as e:
        print(f"Error sending email: {e}")
JavaScript

The send_email() function handles sending the actual email to the recipient. It creates a MIME message with the subject, recipient’s email, and body text, which contains the price and a link to the product. Using Python’s module smtplib, the function logs into your Gmail account formats the email, and sends it. This feature is particularly useful for automating notifications when the price of a product falls below your desired threshold.

For more such content and regular updates, follow us on FacebookInstagramLinkedIn

4. Define the function to run the tracker:

def run_price_tracker(url, target_price, email):
    print("Checking price for the product...")
    check_price(url, target_price, email)
JavaScript

This function is responsible for displaying the message “checking the price for the product” and then calling the check_ price function.

5. Providing the data to start performing the tasks:

url = 'https://www.decathlon.in/p/8733469/jogging-shoes/jogflow-100-superior-grip-cushioned-men-running-shoes-max-10km-wk-navy-orange?id=8733469&type=p'
target_price = float(120000)  # Set your target price
email = 'Youremailid'

run_price_tracker(url,target_price,email)
JavaScript

Here you have to create variables URL, target_price, and email to pass into the functions as arguments. These variables can also be used using input(), depending on whether you need it or not. Then the run_price_tracker function is called to start the tasks of this program.

Conclusion: This Decathlon’s Price Tracker is just the beginning of what you can achieve with Python and data science. The skills you learn from projects like this—data extraction, automation, and analysis—are fundamental in many industries today. By understanding the basics of web scraping, working with APIs, and automating tasks, you can begin building more advanced data science solutions.

Why You Should Learn Data Science!

Data Science is one of the most in-demand skills today, spanning a wide array of fields such as e-commerce, healthcare, finance, and more. In this project, you’ve scratched the surface by working with data extraction and automation. Data Science enables businesses to derive insights from raw data, make better decisions, and predict future trends.

By learning data science, you open up career opportunities in fields like machine learning, artificial intelligence, data analysis, and business intelligence. You can build practical tools, analyze large datasets, and create models that drive business success.

If you’re excited about what you can do with Python, data, and automation, then a Data Science course is the perfect next step. Our Data Science course will teach you everything you need to know, from beginner-level Python to advanced data science concepts such as machine learning, statistical modeling, and data visualization.

Read more about DATA SCIENCE

Here’s how a data science course can benefit you:

High Demand: The demand for data scientists continues to grow as organizations increasingly rely on data-driven decision-making.

Diverse Career Paths: Data science skills are applicable in numerous fields, including finance, healthcare, marketing, and technology.

Lucrative Salaries: Data scientists are among the highest-paid professionals in the tech industry.

Continuous Learning: Data science is a field that constantly evolves, offering endless opportunities for growth and learning.

If you’re ready to embark on a rewarding career in data science, consider enrolling in a comprehensive course that focuses on Python.

At ConsoleFlare, we offer tailored courses that provide hands-on experience and in-depth knowledge to help you master Python and excel in your data science journey. Join us and take the first step towards becoming a data science expert with Python at your fingertips.

Register yourself with ConsoleFlare for our free workshop on data science. In this workshop, you will get to know each tool and technology of data analysis from scratch that will make you skillfully eligible for any data science profile.

Thinking, Why Console Flare?

  • Recently, ConsoleFlare has been recognized as one of the Top 10 Most Promising Data Science Training Institutes of 2023.
  • Console Flare offers the opportunity to learn Data Science in Hindi, just like how you speak daily.
  • Console Flare believes in the idea of “What to learn and what not to learn” and this can be seen in their curriculum structure. They have designed their program based on what you need to learn for data science and nothing else.
  • Want more reasons,

Register yourself  & we will help you switch your career to Data Science in just 6 months.

The Complete Code:

import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def check_price(url,target_price,email):

    try:
        response=requests.get(url)
        soup=BeautifulSoup(response.content,'html.parser')
        price=soup.find('span',{'class':"text-26 mr-4 font-bold text-black"}).get_text()
        price=price.strip().replace('','').replace(',','')
        price=float(price)
        print(f'current price:{price}')

        if price<=target_price:
            print(f'Price drop detected:₹{price} ! sending mail to {email}')
            sendmail(email,url,price)
        else:
            print(f'No price drop detected. the current price is still ₹ {price}. Target price is {target_price}')
    except Exception as e:
        print(f'Error occured while checking the price:{e}')


def sendmail(to_email,product_url,price):
    from_email='arnavmishra643@gmail.com'
    from_password='liqykdpwauqtdddl'

    msg= MIMEMultipart()
    msg['From']=from_email
    msg['To']=to_email
    msg['Subject']=f'Price Drop Alert:₹ {price}'

    body=f'The price of the product is dropped to ₹ {price}. Chect it out here {product_url}'
    msg.attach(MIMEText(body,'plain'))

    try:
        server=smtplib.SMTP('smtp.gmail.com',587)
        server.starttls()
        server.login(from_email,from_password)
        text=msg.as_string()
        server.sendmail(from_email,to_email,text)
        server.quit()
        print(f'Email sent successfully to {to_email} about the price drop')

    except Exception as e:
        print(f'Error in sending mail:{e}')

def run_tracker(url,target_price,email):
    print('Checking the price for the product')
    check_price(url,target_price,email)




url='https://www.decathlon.in/p/8560773/road-bikes/road-bike-van-rysel-rcr900-af-uci-approved-shimano-105-groupset-92kg-in-m?id=8560773&type=p'
target_price=200000
email='arnavmishra643@gmail.com'
run_tracker(url,target_price,email)
JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top