import requests
from bs4 import BeautifulSoup
import smtplib
import getpass
def get_price():
''' the url from which u need the product details '''
URL = 'https://www.amazon.in/JBL-Splash-Proof-Portable-Wireless-Bluetooth/dp/B0125QA4IO?ref_=Oct_DLandingS_PC_a25847b7_13'
''' user-agent involved: search for 'my user agent' in your browser to get this info '''
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'}
''' get the whole page; if u print 'page' it will be nasty and big '''
page = requests.get(URL, headers = headers)
''' parse the page (using html parser) '''
soup = BeautifulSoup(page.content, 'html.parser')
''' find the id (aka variable) used in browser that holds product info '''
product = soup.find(id = 'productTitle').get_text().strip()
''' similarly get the price '''
price = soup.find(id = 'priceblock_ourprice').get_text().strip()
print (product)
print (price)
''' some manipulation needed to get the price in value (instead of string) '''
converted_price = price.strip('₹').strip()
converted_price = float(converted_price.replace(',', ''))
print (converted_price)
return converted_price
def send_mail(mailid, password, current_price):
''' get the SMTP object '''
server = smtplib.SMTP('smtp.gmail.com', 587)
''' extended hello '''
server.ehlo()
''' put the smtp connection in tls mode; this to get encrypted connection '''
server.starttls()
server.ehlo()
''' login using your credentials '''
server.login(mailid, password)
#subject = 'Hey, the price fell down to ₹ {}/-'.format(current_price).encode('utf-8')
#subject = 'Hey, the price fell down to ₹ %s' % (str(current_price)).encode('utf-8')
subject = 'Hey, the price fell down'
body = 'Check the amazon link for more details: https://www.amazon.in/JBL-Splash-Proof-Portable-Wireless-Bluetooth/dp/B0125QA4IO?ref_=Oct_DLandingS_PC_a25847b7_13' msg = f"Subject: {subject}\n\n{body}" server.sendmail('hkumar.sekar@gmail.com', 'harish.sekar@broadcom.com', msg)
''' don't forget to delete the smtp object aka. close connection '''
server.quit()
print ("Hey, the price dropped. Mail is sent")
def main():
mailid = input('Enter your email ID: ')
p = getpass.getpass()
current_price = get_price()
if current_price < 6000:
send_mail(mailid, p, current_price)
if __name__ == '__main__':
main()
PROGRAM OUTPUT:
C:\Users\hs411053\PycharmProjects\scraper\venv\Scripts\python.exe C:/Users/hs411053/PycharmProjects/scraper/scraper
Enter your email ID: hkumar.sekar@gmail.com
Password:
JBL Flip 3 Portable Wireless Speaker with Powerful Sound & Mic (Blue)
₹ 5,599.00
5599.0
Hey, the price dropped. Mail is sent
Process finished with exit code 0
And the Mail would have been sent.