To create an Amazon price tracker with Python, we will need to use several libraries including requests, bs4 (beautifulsoup) and smtplib (for sending email notifications).
First, we need to import the necessary libraries:
import requests
from bs4 import BeautifulSoup
import smtplib
Next, we will use the requests library to make a GET request to the Amazon product page. We will then use the beautifulsoup library to extract the product price.
URL = 'https://www.amazon.com/product-page-url'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;Win64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'}
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
price = soup.find(id='priceblock_ourprice').get_text()
In the above code snippet we are getting the product page from amazon website and using the beautifulsoup library to parse the html and getting the price of the product.
Next, we will check if the price is below a certain threshold and, if so, send an email notification using the smtplib library.
THRESHOLD = 10.00
if float(price[1:]) < THRESHOLD:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('your_email', 'your_password')
subject = 'Price fell down!'
body = f'Check the amazon link {URL}'
msg = f'Subject: {subject}\n\n{body}'
server.sendmail(
'your_email',
'to_email',
msg
)
print('Email has been sent!')
server.quit()
In the above code snippet we are checking if the price of the product is less than the threshold value, if so we are sending email notification to the user.
You can run this script on schedule, for example using a cron
job or windows task scheduler, in order to track the price of the product periodically.
Please note that you will need to enable “less secure apps” in your gmail account in order to use the smtplib library. Also, this is a simple example, you may have to tweak the code to make it work with the exact product page you are trying to track.