-
Notifications
You must be signed in to change notification settings - Fork 0
/
hsnNoDB.py
146 lines (123 loc) · 5.01 KB
/
hsnNoDB.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#######################################################
# #
# HSNscrapper #
# Author: Adrián Pino #
# #
#######################################################
# Import necessary libraries for the script
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
import sys
import time
# Import libraries for handling environment variables and making HTTP requests
from dotenv import load_dotenv
import os
import requests
import json
# Load environment variables from a .env file
load_dotenv()
# Retrieve user credentials and tokens from environment variables
userlogin = os.getenv('USERLOGIN')
password = os.getenv('PASSWORD')
token = os.getenv('TOKEN')
chat_ids_json = os.environ.get('HSN_CHAT_IDS')
chat_ids = json.loads(chat_ids_json)
# Define the Telegram API endpoint for sending messages
telegram_api_send_msg = f'https://api.telegram.org/bot{token}/sendMessage'
def telegramMSG(str):
"""
Send a message to a Telegram chat using the Telegram Bot API.
Args:
str (str): The message to send.
Returns:
None
"""
for chat_id in chat_ids:
data = {
'chat_id': chat_id,
'text': f'{str}',
'parse_mode': 'Markdown'
}
r = requests.post(telegram_api_send_msg, data=data)
def login(driver):
"""
Perform a login action on a website using the provided Selenium WebDriver.
Args:
driver: The Selenium WebDriver instance.
Returns:
None
"""
try:
driver.get('https://www.hsnstore.com/customer/account/login/')
driver.find_element(By.CSS_SELECTOR, '.cookiebar-close').click()
driver.find_element(By.CSS_SELECTOR, 'input[name="login[username]"]').send_keys(userlogin)
driver.find_element(By.CSS_SELECTOR, 'input[type="password"]').send_keys(password)
driver.find_element(By.CSS_SELECTOR, 'button#send2.btn.btn-orange-transparent.customligin_button').click()
except Exception as e:
msg = (f"Error in login: {e}")
print(msg)
# telegramMSG(msg)
sys.exit()
def get_data():
"""
Scrape data from a website, extract product information, and return it as a list of dictionaries.
Returns:
list: A list of product dictionaries containing 'name', 'price', and 'url'.
Returns None on error.
"""
try:
options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.maximize_window()
login(driver)
time.sleep(10)
driver.get("https://www.hsnstore.com/checkout/cart/")
time.sleep(10)
driver.execute_script("window.scrollTo(0, 350);")
time.sleep(10)
products = []
product1 = {
"name": driver.find_element(By.CSS_SELECTOR, "div.item:nth-of-type(1) .product-name a").text.upper().split(" - ")[0],
"price": driver.find_element(By.CSS_SELECTOR, "div.item:nth-of-type(1) .col-sm-7 span.price").text.replace(" ", ""),
"url": "https://www.hsnstore.com/marcas/sport-series/evowhey-protein-2-0-2kg-chocolate"
}
products.append(product1)
product2 = {
"name": driver.find_element(By.CSS_SELECTOR, "div:nth-of-type(2) .product-name a").text.upper().split(" - ")[0],
"price": driver.find_element(By.CSS_SELECTOR, 'div:nth-of-type(2) .col-xs-12 .col-xs-12 .cart-price span').text.replace(" ", ""),
"url": "https://www.hsnstore.com/marcas/sport-series/evocasein-2-0-caseina-micelar-digezyme-2kg-chocolate"
}
products.append(product2)
driver.quit()
print(products)
return products
except Exception as e:
msg = (f"Error while fetching data: {e}")
print(msg)
# telegramMSG(msg)
return None
sys.exit()
if __name__ == '__main__':
try:
# Fetch product data from a website
products = get_data()
# Iterate through the list of products
for product in products:
product_name = product["name"]
product_price = product["price"]
product_url = product["url"]
brand = "HSN"
# Check if product information is available
if product_name and product_price and product_url:
# Create a message to notify about the price
msg = f"*{brand} |* [{product_name}]({product_url}) *| {product_price}*"
print(msg)
telegramMSG(msg)
except Exception as e:
# Handle exceptions and display an error message
msg = (f"Error sending and/or storing the data: {e}")
print(msg)
# telegramMSG(msg)
sys.exit()