Allison is coding...

100 Days of Code: Day 47

Notes of 100 Days of Code: The Complete Python Pro Bootcamp.

To write an Amazon price tracker script:

  • Use request and BeautifulSoup to parse the product url
  • Use smtplib to send Email notification
  • Use os and dotenv to store personal information .env file

Steps:

  • Get price
  • Set an aim price and compare it to current price
  • If lower than aim price, send Email

Sample code:

from requests import get
from bs4 import BeautifulSoup
import os
from dotenv import load_dotenv
import smtplib

load_dotenv()

SMTP_ADDRESS = os.getenv("SMTP_ADDRESS")
EMAIL = os.getenv("EMAIL_ADDRESS")
PASSWORD = os.getenv("EMAIL_PASSWORD")
RECEIVER_EMAIL = os.getenv("RECEIVER_EMAIL")

## Get Price

url = "https://www.amazon.com/SAMSUNG-Chromebook-Plus-Touchscreen-Education/dp/B0DB5RQ3LR/"

header = {
     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8"
 }

response = get(url, headers = header)

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

price = int(soup.find(class_= "a-price-whole").get_text().split(".")[0])
product_title = soup.find(id="productTitle").get_text().strip()

print(price)

## Send Email

BUY_PRICE = 220

if price < BUY_PRICE:
    message = f"The {product_title} price is below {BUY_PRICE}, buy now!"

    with smtplib.SMTP(SMTP_ADDRESS, 587) as server:
        server.starttls()
        server.login(EMAIL, PASSWORD)
        server.sendmail(
            from_addr=EMAIL,
            to_addrs=RECEIVER_EMAIL,
            msg=f"Subject:Amazon Price Alert!\n\n{message}\n{url}".encode("utf-8")
        )