DEV Community

qing
qing

Posted on

Build a Subscription Box Price Tracker with Python

Build a Subscription Box Price Tracker with Python

Build a Subscription Box Price Tracker with Python

You’re paying for a subscription box every month, but have you noticed the price creeping up? Maybe it started at $29 and now it’s $34, or a “limited-time” discount disappeared overnight. Instead of manually checking the site every week, you can build a Python-powered price tracker that monitors subscription box costs and alerts you when they drop—or warns you before they rise.

This isn’t just about saving a few dollars. It’s about taking control of your spending with code you can run today.

Why Build a Subscription Box Price Tracker?

Subscription boxes are everywhere: beauty, snacks, books, pet supplies, and more. Companies often adjust prices subtly, remove discounts, or introduce new tiers. Without tracking, you might miss:

  • Price hikes that happen without announcement
  • Temporary discounts that vanish quickly
  • Better deals on competitor products

A simple tracker gives you data-driven insights and automated alerts, turning passive spending into active decision-making.

What You’ll Build

In this guide, you’ll create a script that:

  1. Fetches the current price from a subscription box product page
  2. Compares it to your target price
  3. Sends an email alert if the price drops below your threshold
  4. Logs price history to a CSV file for later analysis

You’ll use Python, requests, BeautifulSoup, and SMTP—all standard libraries or easily installable packages.

Step 1: Set Up Your Environment

First, create a dedicated folder and install the required libraries:

mkdir subscription_price_tracker
cd subscription_price_tracker
pip install requests beautifulsoup4 pandas
Enter fullscreen mode Exit fullscreen mode

Note: pandas helps structure data, and requests + beautifulsoup4 handle web scraping.

Create a file named price_tracker.py and start importing:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
Enter fullscreen mode Exit fullscreen mode

Step 2: Fetch and Parse the Price

Most subscription box sites display prices in a predictable HTML structure. Let’s write a function to extract it.

Here’s a working example that scrapes a sample product page (you’ll replace the URL with your target):

def get_price(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        raise Exception(f"Failed to fetch page: {response.status_code}")

    soup = BeautifulSoup(response.text, 'html.parser')

    # Adjust this selector based on the actual site's HTML
    price_element = soup.find("span", class_="price")  # Example selector

    if not price_element:
        raise Exception("Price element not found. Check the HTML structure.")

    price_text = price_element.get_text(strip=True)
    # Remove currency symbols and convert to float
    price = float(price_text.replace("$", "").replace(",", ""))

    return price
Enter fullscreen mode Exit fullscreen mode

🔍 Important: Replace "span", class_="price" with the actual selector from your target site. Use your browser’s Developer Tools (F12) to inspect the price element and find its class or tag.

Step 3: Track Prices and Log History

Now, let’s wrap the price fetching into a tracking loop that logs results to a CSV file.

def track_price(url, target_price, csv_file="price_history.csv"):
    current_price = get_price(url)
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")

    # Load existing data or create new DataFrame
    if pd.path.exists(csv_file):
        df = pd.read_csv(csv_file)
    else:
        df = pd.DataFrame(columns=["timestamp", "url", "price"])

    # Append new row
    new_row = pd.DataFrame({
        "timestamp": [timestamp],
        "url": [url],
        "price": [current_price]
    })
    df = pd.concat([df, new_row], ignore_index=True)
    df.to_csv(csv_file, index=False)

    print(f"{timestamp} | {url} | Current: ${current_price} | Target: ${target_price}")

    # Check if price is below target
    if current_price <= target_price:
        send_alert(url, current_price, target_price)

    return current_price
Enter fullscreen mode Exit fullscreen mode

Step 4: Send Email Alerts

When the price drops, you’ll want to know immediately. Here’s how to send an email using Python’s built-in smtplib:

def send_alert(url, current_price, target_price):
    mail_user = "your_email@gmail.com"
    mail_pass = "your_app_password"  # Use app password, not main password
    mail_to = "alert_recipient@example.com"

    subject = f"🎉 Price Drop Alert: {url}"
    body = f"""
    The subscription box at {url} is now ${current_price}, 
    which is below your target of ${target_price}.

    Time to buy!
    """

    msg = MIMEText(body)
    msg["Subject"] = subject
    msg["From"] = mail_user
    msg["To"] = mail_to

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(mail_user, mail_pass)
        server.send_message(msg)

    print("✅ Alert email sent!")
Enter fullscreen mode Exit fullscreen mode

🔐 Security Tip: Never hardcode passwords. Use environment variables or a .env file. For Gmail, generate an App Password instead of using your main password.

Step 5: Run the Tracker Automatically

To check prices daily, you can schedule the script:

  • On Windows: Use Task Scheduler to run a batch file that executes python price_tracker.py
  • On macOS/Linux: Use cron:
  crontab -e
  # Add this line to run every day at 9 AM:
  0 9 * * * python /path/to/subscription_price_tracker/price_tracker.py
Enter fullscreen mode Exit fullscreen mode

Real-World Tips for Success

  • Handle Anti-Scraping: Some sites block bots. Add headers (as shown) and consider using time.sleep() between requests to avoid flooding.
  • Dynamic Prices: If the site uses JavaScript to load prices, requests + BeautifulSoup won’t work. Use Selenium or Playwright instead.
  • Multiple Products: Loop through a list of URLs to track several subscription boxes at once.
  • Visualize Trends: Use matplotlib to plot price history from your CSV and spot patterns.

What You Can Do Today

You don’t need to wait. Here’s your action plan:

  1. Pick one subscription box you’re subscribed to (or interested in).
  2. Open its product page and inspect the price HTML element.
  3. Replace the selector in get_price() with the correct one.
  4. Set your target_price and run the script once.
  5. If it works, schedule it to run daily.

You’ll have a personal price watchdog in under an hour.

Final Thoughts

Building a subscription box price tracker isn’t just a coding exercise—it’s a practical tool that puts you in control. You’ll catch price drops, avoid hidden hikes, and make smarter purchasing decisions. Plus, the skills you learn (web scraping, automation, email alerts) apply to countless other projects.

Ready to start? Clone the code, tweak it for your favorite box, and run it today. If you build something cool, share it on Dev.to and tag it with #python, #automation, or #datascience. Let’s see what you create!


If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!

Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.

Top comments (0)