DEV Community

Cover image for How To Build a Price Tracker Bot in Python From Scratch
Sudhir Bahadure
Sudhir Bahadure

Posted on

How To Build a Price Tracker Bot in Python From Scratch

Introduction

Did you know that online prices can fluctuate by as much as 20% in a single day, resulting in potential losses for consumers and businesses alike? In this tutorial, you will build a price tracker bot in Python from scratch, learning how to automate the process of monitoring prices and receiving alerts when they change. To get started, you'll need to have Python 3.8 or later installed on your system, along with a basic understanding of Python programming and access to a web browser for testing.

Table of Contents

  1. Introduction
  2. Setup and Background
  3. Step 1: Inspect the Website and Extract Price Information
  4. Step 2: Store Price Data and Send Alerts
  5. Real-World Application and Next Steps
  6. Conclusion

Setup and Background

python automation
To build a price tracker bot, we first need to understand the basics of web scraping and automation. Web scraping involves extracting data from websites, which can be done using Python libraries like requests and BeautifulSoup. Before we dive into the code, let's create a new Python project and install the required libraries. Run the following command in your terminal:

mkdir price_tracker
cd price_tracker
python -m venv env
source env/bin/activate
pip install requests beautifulsoup4
Enter fullscreen mode Exit fullscreen mode

This will create a new project directory, activate a virtual environment, and install the required libraries.

Step 1: Inspect the Website and Extract Price Information

For this example, let's use an online shopping website like Amazon. We'll extract the price of a product and store it in a variable. First, inspect the website and find the HTML element that contains the price information. Then, use the following Python code to extract the price:

import requests
from bs4 import BeautifulSoup

# Send a GET request to the website
url = "https://www.amazon.com/dp/B076MX9VG9"
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})

# Parse the HTML content using BeautifulSoup
soup = BeautifulSoup(response.content, "html.parser")

# Find the price element and extract the text
price_element = soup.find("span", {"class": "a-price-whole"})
price = price_element.text.strip()

print(price)
Enter fullscreen mode Exit fullscreen mode

This code sends a GET request to the website, parses the HTML content, and extracts the price information. The User-Agent header is used to simulate a browser request.

Step 2: Store Price Data and Send Alerts

To store the price data, we'll use a simple YAML file. We'll also set up a basic alert system that sends an email when the price changes. First, install the required libraries:

pip install yaml smtplib
Enter fullscreen mode Exit fullscreen mode

Then, use the following Python code to store the price data and send alerts:

import yaml
import smtplib
from email.mime.text import MIMEText

# Load the current price data from the YAML file
with open("price_data.yaml", "r") as f:
    price_data = yaml.safe_load(f)

# Check if the price has changed
if price != price_data["current_price"]:
    # Send an email alert
    msg = MIMEText(f"Price alert: {price}")
    msg["Subject"] = "Price Tracker Alert"
    msg["From"] = "your_email@gmail.com"
    msg["To"] = "recipient_email@gmail.com"

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login("your_email@gmail.com", "your_password")
    server.sendmail("your_email@gmail.com", "recipient_email@gmail.com", msg.as_string())
    server.quit()

    # Update the YAML file with the new price
    price_data["current_price"] = price
    with open("price_data.yaml", "w") as f:
        yaml.dump(price_data, f)
Enter fullscreen mode Exit fullscreen mode

This code loads the current price data from the YAML file, checks if the price has changed, and sends an email alert if necessary. It also updates the YAML file with the new price.

Step 3: Schedule the Price Tracker Bot

To schedule the price tracker bot to run at regular intervals, we can use a cron job on Linux or a scheduled task on Windows. For this example, let's use a cron job. Open the crontab editor:

crontab -e
Enter fullscreen mode Exit fullscreen mode

Add the following line to schedule the bot to run every hour:

0 * * * * python /path/to/price_tracker-bot.py
Enter fullscreen mode Exit fullscreen mode

Replace /path/to/price_tracker-bot.py with the actual path to your Python script.

Step 4: Test the Price Tracker Bot

To test the price tracker bot, run the Python script manually:

python price_tracker-bot.py
Enter fullscreen mode Exit fullscreen mode

This will send a GET request to the website, extract the price information, and store it in the YAML file. If the price has changed, it will send an email alert.

Real-World Application and Next Steps

The price tracker bot can be used to monitor prices for various products and services, such as NordVPN (68% off + 3 months free) or Hostinger (up to 80% off hosting). You can also use it to track prices for Namecheap (cheapest domains online) or other online services. To take your automation skills to the next level, check out the next article in the Python Automation Mastery series, where we'll cover more advanced topics like automating tasks with Selenium and using machine learning for automation.

Conclusion

In this tutorial, you built a price tracker bot in Python from scratch, learning how to automate the process of monitoring prices and receiving alerts when they change. The three main takeaways from this tutorial are:

  • How to use web scraping to extract price information from websites
  • How to store price data in a YAML file and send email alerts when the price changes
  • How to schedule the price tracker bot to run at regular intervals using a cron job To continue learning, check out the next article in the Python Automation Mastery series, where we'll cover more advanced topics and provide hands-on tutorials to help you master automation with Python.

Top comments (0)