-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprice_tracker.py
More file actions
92 lines (78 loc) · 4.29 KB
/
price_tracker.py
File metadata and controls
92 lines (78 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# price_tracker.py
import requests
from bs4 import BeautifulSoup
import smtplib
import os
# --- CONFIGURATION ---
TARGET_PRICE = 6000.00
PRODUCT_URL = "https://www.amazon.ae/HP-16-an0003nr-Processor-GeForce-DDR5-5600/dp/B0FLDSHLFJ/ref=sr_1_11?crid=3SXWAIZO91G3S&dib=eyJ2IjoiMSJ9.cRzixta9w1LycTWs8rMqGcMvGAs6w-g3rR3CZ2oc7NLQHnOBrqmoYUejXH2ohO-anjvBH5JzxMmFgzprYio_eERy_LqXmx9b5-N-iRQ0kJ8vHSFzrgGtl6E5R64_Gen92pGqmLcJPA9ipwrtXQ4Rc7T2UMc6yvzTivYsz7UaJHl9vv-OXO5iK-KhDGd-jCEJi9JxtynZf0DCwYQJetpdzdEurN4Zq0rpf4IttXSbh6o7vXNCWSFFZwlNzqgEZXke3Zi_Ny45yWPzYke41fknJsenbue9FdEt1ctIUesZU1Y.gGYDcZM62brH9Ycq8B7YEhYxpyNWBsm6ndXayw0IssQ&dib_tag=se&keywords=hp+omen+rtx+4070&qid=1755454294&sprefix=%2Caps%2C268&sr=8-11"
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Encoding": "gzip, deflate, br",
"DNT": "1",
"Upgrade-Insecure-Requests": "1"
}
# --- EMAIL CONFIGURATION ---
SENDER_EMAIL = os.environ.get('SENDER_EMAIL')
SENDER_PASSWORD = os.environ.get('SENDER_PASSWORD')
RECIPIENT_EMAIL = os.environ.get('RECIPIENT_EMAIL')
# --- FUNCTIONS ---
def send_notification(product_name, price):
"""Sends an email notification using SMTP."""
try:
with smtplib.SMTP("smtp.gmail.com", port=587) as connection:
connection.starttls()
connection.login(user=SENDER_EMAIL, password=SENDER_PASSWORD)
connection.sendmail(
from_addr=SENDER_EMAIL,
to_addrs=RECIPIENT_EMAIL,
msg=f"Subject: Price Drop Alert!\n\nThe price for '{product_name}' has dropped to {price} AED!\n\nBuy it now at: {PRODUCT_URL}".encode('utf-8')
)
print("Email notification sent successfully!")
except smtplib.SMTPAuthenticationError:
print("Failed to send email: Authentication error. Check your email/password or App Password.")
except Exception as e:
print(f"An error occurred while sending the email: {e}")
def check_price():
"""Scrapes the product page, checks the price, and sends an email if it's a good deal."""
try:
print("Checking price...")
response = requests.get(PRODUCT_URL, headers=HEADERS)
response.raise_for_status()
soup = BeautifulSoup(response.content, "html.parser")
# --- Find Title (with safety check) ---
product_title_element = soup.find(id="productTitle")
if not product_title_element:
print("Could not find the product title. Page structure may have changed.")
return # Exit the function if title not found
product_title = product_title_element.get_text().strip()
# --- Find Price (with safety check and new selector) ---
# Amazon sometimes hides the main price in a span with class 'a-offscreen'
price_element = soup.select_one("span.a-offscreen")
if not price_element:
print("Could not find the price. Page structure may have changed.")
return # Exit the function if price not found
# The price text might include the currency symbol, e.g., "AED2,739.00"
price_str = price_element.get_text().strip()
# Clean the string to get only the number
price_cleaned = ''.join(filter(lambda x: x.isdigit() or x == '.', price_str))
current_price = float(price_cleaned)
print(f"Product: {product_title}")
print(f"Current Price: {current_price} AED")
if current_price <= TARGET_PRICE:
print("DEAL ALERT! Price is below target. Sending notification...")
send_notification(product_title, current_price)
else:
difference = current_price - TARGET_PRICE
print(f"Not a deal yet. The price is still {difference:.2f} AED above your target.")
except requests.exceptions.RequestException as e:
print(f"HTTP Request failed: {e}")
except (AttributeError, ValueError) as e:
print(f"Failed to parse page or price. Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# --- SCRIPT EXECUTION ---
if __name__ == "__main__":
check_price()