Advertisement
jackox

itemalert4.py

Jun 20th, 2024 (edited)
697
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.41 KB | None | 0 0
  1. #ItemAlert v4
  2. #itemalert4.py
  3.  
  4. from selenium import webdriver
  5. from selenium.webdriver.common.by import By
  6. from selenium.webdriver.common.keys import Keys
  7. from datetime import datetime
  8. from urllib.parse import quote
  9. from urllib.request import urlopen
  10.  
  11. import time
  12. import re
  13. import configparser
  14. import logging
  15. import sys
  16.  
  17. def consultabd(eburl):
  18.     import sqlite3
  19.  
  20.     con = sqlite3.connect('itemalert.db', isolation_level = None)
  21.     cur = con.cursor()
  22.     res = cur.execute("CREATE TABLE IF NOT EXISTS BD (id INTEGER PRIMARY KEY,EBURL text NOT NULL)")
  23.     res = cur.execute("SELECT * FROM BD WHERE EBURL='" + eburl + "'")
  24.     row = res.fetchone()
  25.     if row is None:
  26.         cur.execute("INSERT INTO BD (EBURL) VALUES ('"+ eburl +"')")
  27.         return 0
  28.     else:
  29.         return 1
  30.     con.close()
  31.  
  32. def enviadatos(micodigo,midispositivo,mensaje,desc,eburl,precio,imagen):
  33.     from urllib.request import urlopen
  34.     import urllib.parse
  35.     import logging
  36.     import sys
  37.  
  38.     try:
  39.         url = "https://script.google.com/macros/s/" + micodigo + "/exec?disp=" + str(midispositivo) + "&mensaje=" + mensaje  + "&desc=" + urllib.parse.quote(desc)  + "&eburl=" + eburl  + "&precio=" + urllib.parse.quote(precio)  + "&imagen=" + imagen
  40.         print(url)
  41.         req = urlopen(url)
  42.     except Exception:
  43.         e = sys.exc_info()[1]
  44.         print (e)
  45.         pass
  46.  
  47. logging.basicConfig(filename='ia.log', filemode='a', level=logging.INFO, format='%(asctime)s :: %(levelname)s :: %(message)s')
  48. logging.info("Iniciando ...")
  49. print ("Iniciando ...")
  50.  
  51. logging.info("Consultandeo configuracion local ...")
  52. print ("Consultandeo configuracion local ...")
  53. config = configparser.ConfigParser()
  54. config.read('config.ini')
  55. midispositivo = config['DISPOSITIVO']['ID']
  56. url = config['GSHEET']['URL']
  57.  
  58. logging.info("Consultandeo configuracion online ...")
  59. print ("Consultandeo configuracion online ...")
  60. with urllib.request.urlopen(url) as response:
  61.    html = response.read().decode('utf-8')
  62.  
  63. regex = r"---.*?--(.*?)--.*?---"
  64. r1 = re.findall(regex, html)
  65. miusuario = r1[3]
  66. mipass = r1[4]
  67. mibusqueda = r1[5]
  68. micodigo = r1[6]
  69.  
  70. options = webdriver.ChromeOptions()
  71. options.add_argument("--no-sandbox")
  72. options.add_argument("--disable-dev-shm-usage")
  73. options.add_argument("--headless=new")
  74. driver = webdriver.Chrome(options=options)
  75. driver.get("https://itemalert.com/login")
  76. usuario = driver.find_element(By.NAME, 'username')
  77. pswrd = driver.find_element(By.NAME, 'password')
  78. usuario.send_keys(miusuario)
  79. pswrd.send_keys(mipass)
  80. pswrd.send_keys(Keys.RETURN)
  81. logging.info("Logeado en itemalert")
  82.  
  83. driver.get("https://itemalert.com/savedsearch")
  84. cv = driver.find_element(By.NAME, mibusqueda)
  85. cv.click()
  86.  
  87. go = driver.find_element(By.NAME, 'go')
  88. driver.execute_script("arguments[0].click();", go)
  89. #go.click()
  90.  
  91. email = driver.find_element(By.XPATH,'//p[@data-original-title="new result email"]')
  92. email.click()
  93.  
  94. eterror = driver.find_element(By.XPATH,'//div[@id="error"]')
  95. errorat = eterror.get_attribute('innerHTML')
  96.  
  97. logging.info("Monitoreo iniciado, mensaje: " + errorat)
  98. j = 0
  99. while True:
  100.        symbols = str(datetime.now())
  101.        nomimg = "captura-" + "".join(symbols) + ".png"
  102.        nomimg = nomimg.replace(":","")
  103.        nomimg = nomimg.replace(" ","")
  104.        eterror = driver.find_element(By.XPATH,'//div[@id="error"]')
  105.        errorat = eterror.get_attribute('innerHTML')
  106.        errorat = re.sub(r'<[^>]*?>', '', errorat)
  107.        errorat = errorat.replace(" ","")
  108.        errorat = quote(errorat)
  109.        logging.info("Error: " + errorat)
  110.  
  111.        if(errorat == "NoeBayErrors%21"):
  112.               if(j == 15):
  113.                   j = 1
  114.                   print("Enviando aviso de funcionamiento")
  115.                   enviadatos(micodigo,midispositivo,errorat,"","","","")
  116.               else:
  117.                   j += 1
  118.               print ("ItemAlert operando sin errores: " + str(j) + " de 15")
  119.               html = driver.execute_script("return document.body.innerHTML")
  120.  
  121.               regex = 'l l-d".*?>(.*?)<\/span>'#Descripciones
  122.               descs = re.findall(regex, html)
  123.               regex = '"p-r" href=.*?itm\/(.*?)\?'#Clave ebay
  124.               eburls = re.findall(regex, html)
  125.               regex = 'Fixed Price @ (.*?) USD|Auction : (.*?) USD'#Precio
  126.               precios = re.findall(regex, html)
  127.               regex = 'images\/g\/(.*?)\/s-l225.jpg'#Imagen
  128.               imagenes = re.findall(regex, html)
  129.               length = len(descs)
  130.               logging.info("Registros encontrados: " + str(length))
  131.               for i in range(length//2):
  132.                      desc = descs[i]
  133.                      eburl = eburls[i]
  134.                      precio = precios[i][0] + precios[i][1]
  135.                      imagen = imagenes[i]
  136.                      nregs = consultabd(eburl)
  137.                      if nregs == 0:
  138.                             print ("Item " + eburl + " NO encontrado en BD")
  139.                             enviadatos(micodigo,midispositivo,"Nuevo_item_encontrado:_" + eburl,desc,eburl,precio,imagen)
  140.                             time.sleep(5)
  141.                      else:
  142.                          print ("Item " + eburl + " encontrado en BD")
  143.               time.sleep(20)
  144.        else:
  145.               logging.info("NO Entro al if error, error:" + errorat)
  146.               print("NO Entro al if error")
  147.               enviadatos(micodigo,midispositivo,errorat,"","","","")
  148.               time.sleep(300)
  149. driver.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement