DEV Community

Brad
Brad

Posted on

Build a Python Price Monitor: Get Alerts When Prices Drop

Build a Python Price Monitor: Get Alerts When Prices Drop

Stop checking prices manually. Build a Python bot that monitors prices and alerts you when they drop.

What It Does

  • Checks product prices on a schedule
  • Stores price history in SQLite
  • Sends email when price drops
  • Works for Amazon, Shopify, any website

Core Code

import requests
import sqlite3
import re
from bs4 import BeautifulSoup
import smtplib
import schedule

def get_price(url):
    headers = {'User-Agent': 'Mozilla/5.0'}
    r = requests.get(url, headers=headers, timeout=10)
    soup = BeautifulSoup(r.text, 'html.parser')
    for sel in ['.price', '#price', '[itemprop=price]']:
        el = soup.select_one(sel)
        if el:
            nums = re.findall(r'[0-9]+[.]?[0-9]*', el.get_text().replace(',',''))
            if nums:
                return float(nums[0])
    return None

def check_prices(conn, watch_list):
    for url, name, target, email in watch_list:
        price = get_price(url)
        if price is None:
            continue
        conn.execute('INSERT INTO prices (url, name, price) VALUES (?,?,?)',
                    (url, name, price))
        conn.commit()

        rows = conn.execute(
            'SELECT price FROM prices WHERE url=? ORDER BY ts DESC LIMIT 2', (url,)
        ).fetchall()
        if len(rows) >= 2:
            prev, curr = rows[1][0], rows[0][0]
            drop = (prev - curr) / prev * 100
            if curr <= target or drop >= 10:
                send_email(email, name, prev, curr, drop)
                print(f'ALERT: {name} dropped {drop:.1f}% to ${curr:.2f}')
Enter fullscreen mode Exit fullscreen mode

Scheduling

conn = sqlite3.connect('prices.db')
watch = [('https://example.com/item', 'Widget', 25.0, 'you@gmail.com')]

schedule.every(1).hours.do(lambda: check_prices(conn, watch))
while True:
    schedule.run_pending()
    import time; time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Run on Raspberry Pi

For 24/7 monitoring at ~$35 one-time cost:

pip3 install requests beautifulsoup4 schedule
python3 price_monitor.py &
Enter fullscreen mode Exit fullscreen mode

Get 12 Scripts for $9

This price monitor plus 11 more automation scripts (invoicing, reporting, email, inventory):

Python Business Automation Toolkit

Instant download, one-time purchase.

Top comments (0)