1
+ import re
1
2
import requests
2
3
import smtplib
3
4
from bs4 import BeautifulSoup
10
11
FROM_PASSWORD = environ .get ("FROM_PASSWORD" )
11
12
TO_EMAIL = environ .get ("TO_EMAIL" )
12
13
13
- URL = "https://www.amazon.in/dp/B09RHCYZ82"
14
+ # Define a regular expression pattern for Amazon product URLs
15
+ amazon_url_pattern = r"https?://(?:www\.)?amazon\.(?:com|ca|co\.uk|de|fr|it|es|co\.jp|com\.au|com\.mx|nl|com\.br|ae|in)/(?:[\w-]+/)?(?:dp|gp/product)/(?:\w{10}|\w{13})"
16
+
17
+ # Keep asking for a valid Amazon product URL from the user
18
+ while True :
19
+ URL = input ("Please provide the URL of the product on Amazon:\n " )
20
+ if re .match (amazon_url_pattern , URL ):
21
+ break
22
+ else :
23
+ print ("Invalid Amazon product URL. Please try again." )
14
24
15
25
http_headers = {
16
26
"Accept-Language" : "en-US,en;q=0.9" ,
20
30
response = requests .get (URL , headers = http_headers )
21
31
soup = BeautifulSoup (response .text , 'html.parser' )
22
32
23
- price = float (soup .find (name = "span" , class_ = "a-offscreen" ).getText ()[1 :])
33
+ price_str = soup .find (name = "span" , class_ = "a-offscreen" ).getText ().replace ("," , "" )
34
+ if price_match := re .search (r"([\d,]+(?:\.\d{1,2})?)" , price_str ):
35
+ price = float (price_match [1 ].replace ("," , "" ))
36
+ else :
37
+ print ("Could not extract price information. Exiting." )
38
+ exit ()
39
+
24
40
product_name = " " .join (soup .find (
25
41
name = "span" , class_ = "a-size-large product-title-word-break" ).getText ().split ())
26
42
27
- if price < 400.00 :
43
+ user_price_str = input ("What amount do you want to compare the product with?\n " )
44
+ if user_price_match := re .search (r"([\d,]+(?:\.\d{1,2})?)" , user_pri ce_str ):
45
+ user_price = float (user_price_match [1 ].replace ("," , "" ))
46
+ else :
47
+ print ("Could not extract user price information. Exiting." )
48
+ exit ()
49
+
50
+ if price < user_price :
28
51
with smtplib .SMTP ("smtp.mail.yahoo.com" , 587 ) as connection :
29
52
connection .starttls ()
30
53
connection .login (FROM_EMAIL , FROM_PASSWORD )
31
54
connection .sendmail (from_addr = FROM_EMAIL ,
32
55
to_addrs = TO_EMAIL ,
33
- msg = f"Subject: Price Drop Alert!\n \n { product_name } is now available in ₹{ price } \n \n Visit: { URL } " .encode ('utf-8' )
56
+ msg = f"Subject: Price Drop Alert!\n \n { product_name } is now available for ₹{ price } \n \n Visit: { URL } " .encode ('utf-8' )
34
57
)
0 commit comments