· 3 months ago · Jul 04, 2025, 12:55 AM
1#!/usr/bin/env python3
2
3import configparser
4import os
5import sqlite3
6import json
7import requests
8from selenium import webdriver
9from selenium.webdriver.common.by import By
10from selenium.webdriver.common.keys import Keys
11from selenium.common.exceptions import WebDriverException
12from urllib.request import urlopen
13import time
14import re
15import urllib.parse
16
17# Cargar variables desde .env
18config = configparser.ConfigParser()
19config.read('config.ini')
20miusuario = config['DATABASE']['USUARIO']
21mipass = config['DATABASE']['PASSWORD']
22mibusqueda = config['DATABASE']['BUSQUEDA_ID']
23gurl = config['DATABASE']['GURL']
24
25def consultabd(eburl):
26 try:
27 con = sqlite3.connect('itemalert.db', isolation_level=None)
28 cur = con.cursor()
29 cur.execute("CREATE TABLE IF NOT EXISTS BD (id INTEGER PRIMARY KEY, EBURL text NOT NULL)")
30 cur.execute("SELECT * FROM BD WHERE EBURL=?", (eburl,))
31 row = cur.fetchone()
32 if row is None:
33 cur.execute("INSERT INTO BD (EBURL) VALUES (?)", (eburl,))
34 return 0
35 return 1
36 except Exception as e:
37 logWeb(f'Error en consultabd: {str(e)}', 1)
38 return 1
39 finally:
40 con.close()
41
42def almacenabd():
43 try:
44 con = sqlite3.connect('itemalert.db', isolation_level=None)
45 cur = con.cursor()
46 cur.execute("DROP TABLE IF EXISTS BD")
47 cur.execute("CREATE TABLE IF NOT EXISTS BD (id INTEGER PRIMARY KEY, EBURL text NOT NULL)")
48 response = requests.get(gurl)
49 data = response.json()
50 array = json.loads(data)
51 for item in array:
52 cur.execute("INSERT INTO BD (EBURL) VALUES (?)", (str(item[0]),))
53 except Exception as e:
54 logWeb(f'Error en almacenabd: {str(e)}', 1)
55
56def publicaciones(html, items, precios, descs, imgs):
57 try:
58 regex = r'media result resultnew ohtoe m-b".*?>(.*?)<\/div>'
59 publicaciones = re.findall(regex, html)
60 npubs = int(len(publicaciones)/2)
61
62 for i in range(npubs):
63 pub = publicaciones[i]
64
65 desc_regex = r'l l-d".*?>(.*?)<\/span>'
66 desc_match = re.findall(desc_regex, pub)
67 descs.append(desc_match[0] if desc_match else "")
68
69 img_regex = r'images\/g\/(.*?)\/s-l225.jpg'
70 img_match = re.findall(img_regex, pub)
71 imgs.append(img_match[0] if img_match else "")
72
73 item_regex = r'"p-r" href=.*?itm\/(.*?)\?'
74 item_match = re.findall(item_regex, pub)
75 items.append(item_match[0] if item_match else "")
76
77 price_regex = r'Fixed Price @ (.*?) USD|Auction : (.*?) USD'
78 price_match = re.findall(price_regex, pub)
79 if price_match:
80 price = price_match[0][0] or price_match[0][1]
81 clean_price = re.sub(r"[(),' ]", "", str(price))
82 precios.append(clean_price)
83 else:
84 precios.append("")
85
86 return npubs
87 except Exception as e:
88 logWeb('Error en publicaciones: ' + str(e), 1)
89 return 0
90
91def logWeb(_log, _prio=0):
92 try:
93 _log = urllib.parse.quote_plus(_log)
94 url = gurl + "?log=" + _log
95 if _prio == 1:
96 urlopen(url)
97 except Exception as e:
98 print(f"Error en logWeb: {str(e)}")
99
100def crear_driver():
101 options = webdriver.ChromeOptions()
102 options.add_argument("--no-sandbox")
103 options.add_argument("--disable-dev-shm-usage")
104 options.add_argument("--disable-gpu")
105 options.add_argument("--disable-extensions")
106 options.add_argument("--disable-background-networking")
107 options.add_argument("--disable-software-rasterizer")
108 options.add_argument("--headless")
109 return webdriver.Chrome(options=options)
110
111# Inicio del programa
112logWeb('Iniciando_ItemAlert.py', 1)
113
114items, precios, descs, imgs = [], [], [], []
115
116driver = crear_driver()
117
118def login_y_busqueda():
119 try:
120 driver.get("https://itemalert.com/login")
121 time.sleep(2)
122 usuario = driver.find_element(By.NAME, 'username')
123 pswrd = driver.find_element(By.NAME, 'password')
124 usuario.send_keys(miusuario)
125 pswrd.send_keys(mipass)
126 pswrd.send_keys(Keys.RETURN)
127 time.sleep(3)
128
129 driver.get("https://itemalert.com/savedsearch")
130 time.sleep(2)
131 cv = driver.find_element(By.NAME, mibusqueda)
132 driver.execute_script("arguments[0].click();", cv)
133 time.sleep(1)
134 go = driver.find_element(By.NAME, 'go')
135 driver.execute_script("arguments[0].click();", go)
136 time.sleep(3)
137
138 except Exception as e:
139 logWeb(f'Error en login_y_busqueda: {str(e)}', 1)
140
141almacenabd()
142login_y_busqueda()
143time.sleep(20)
144i = 15
145
146while True:
147 try:
148 try:
149 html = driver.execute_script("return document.body.innerHTML")
150 except WebDriverException as we:
151 logWeb(f'Tab crashed, reiniciando driver: {str(we)}', 1)
152 driver.quit()
153 driver = crear_driver()
154 login_y_busqueda()
155 time.sleep(20)
156 continue
157
158 eterror = driver.find_element(By.XPATH, '//div[@id="error"]')
159 errorat = re.sub('<.*?>', '', eterror.get_attribute('innerHTML'))
160 errorat = "".join(char for char in errorat if char.isalnum() or char == " ")
161
162 if i >= 15:
163 i = 1
164 logWeb(errorat, 1)
165 else:
166 i += 1
167
168 npubs = publicaciones(html, items, precios, descs, imgs)
169
170 for j in range(npubs):
171 if j < len(items) and items[j]:
172 if consultabd(items[j]) == 0:
173 url = gurl + "?item=" + urllib.parse.quote_plus(str(items[j])) + \
174 "&pre=" + urllib.parse.quote_plus(str(precios[j] if j < len(precios) else "")) + \
175 "&des=" + urllib.parse.quote_plus(str(descs[j] if j < len(descs) else ""))+ \
176 "&img=" + urllib.parse.quote_plus(str(imgs[j] if j < len(imgs) else ""))
177 urlopen(url)
178
179 driver.execute_script("arguments[0].click();", driver.find_element(By.ID, 'cleardom-btn'))
180 items.clear()
181 precios.clear()
182 descs.clear()
183 imgs.clear()
184 time.sleep(20)
185
186 except Exception as e:
187 logWeb(f'Error en bucle principal: {str(e)}', 1)
188 time.sleep(20)