Comprobador de precios de vuelos usando Python y Selenium

Python es un lenguaje de secuencias de comandos con muchas bibliotecas y marcos extendidos. Se utiliza en varios campos de la informática, como el desarrollo web y la ciencia de datos. Además, Python se puede usar para automatizar algunas tareas menores que pueden ser realmente útiles a largo plazo.

La secuencia de comandos de Python mencionada en este artículo obtendrá los precios de paytm.com usando selenium y si es menor o igual a la cantidad (que está listo para gastar) establecida por usted, se enviará una notificación al correo electrónico deseado. ids sobre el precio reducido.

La identificación de correo electrónico que se usará para enviar las notificaciones no debe usar la contraseña personal, ya que requiere la autenticación de dos factores y la acción fallará. Más bien, se debe establecer una contraseña diferente a la que pueda acceder el script y muchas otras aplicaciones diferentes que uno podría desarrollar en el futuro.

Nota: La contraseña requerida para enviar ese correo electrónico se puede configurar a través de este enlace: Contraseñas de aplicaciones de Google

Implementación

Importación de todas las bibliotecas requeridas

Selenium para realizar la automatización del sitio web

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.chrome.options import Options 
from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.common.keys import Keys 

STMPLIB para el envío de notificaciones a través de correos electrónicos

import smtplib

Extraer el precio de los vuelos entre dos fechas seleccionadas

# Choose the two dates
# in this format 
x = "2020-03-10" 
y = "2020-03-16"
  
a = int(x[8:10])
b = int(y[8:10])
  
if a > b:
    m = a - b
    t = b
  
else:
    m = b - a
    t = a
print(t)
  
low_price = ""
url_final = 'https://paytm.com/flights'
data = {}
  
for i in range(t, t + m+1):
    url = 'https://paytm.com/flights/flightSearch/BBI-\
    Bhubaneshwar/DEL-Delhi/1/0/0/E/2020-03-'+str(i)
      
    # Locations can be changed on 
    # the above statement
    print(url)
      
    date = "2019-12-" + str(i)
      
    # enables the script to run properly without 
    # opening the chrome browser.
    chrome_options = Options()
    chrome_options.add_argument("--disable-gpu")
      
  
    chrome_options.add_argument("--headless")
      
    driver = webdriver.Chrome(executable_path = '/path/to/chromedriver', 
                              options=chrome_options)
      
    driver.implicitly_wait(20)
    driver.get(url)
      
    g = driver.find_element_by_xpath("//div[@class='_2gMo']") 
    price = g.text
      
    x = price[0]
    y = price[2:5]
    z = str(x)+str(y)
    p = int(z)
    print(p)
      
    prices=[]
    if p <= 2000:
        data[date] = p
          
for i in data:
    low_price += str(i) + ": Rs." + str(data[i]) + "\n"
      
print(low_price) 

Envío de la notificación si hay vuelos baratos disponibles a través de un correo electrónico mediante SMTP

if len(data) != 0:
      
    dp = 2000
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.ehlo()
    server.starttls()
    server.ehlo()
      
    server.login('your_email_id','your_password')
    subject = "Flight price for BBI-DEL has fallen\
    below Rs. " + str(dp)
      
    body = "Hey Akash! \n The price of BBI-DEL on PayTm \
    has fallen down below Rs." + str(dp) + ".\n So,\
    hurry up & check: " + url_final+"\n\n\n The prices of\
    flight below Rs.2000 for the following days are\
    :\n\n" + low_price
      
    msg = f"Subject: {subject} \n\n {body}"
      
    server.sendmail(
        # email ids where you want to
        # send the notification
        'email_id_1',
        'email_id_2',
        msg
        )
      
    print("HEY,EMAIL HAS BEEN SENT SUCCESSFULLY.")
       
    server.quit()

Código completo:

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.chrome.options import Options 
from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.common.keys import Keys 
import smtplib
  
  
# Choose the two dates
# in this format 
x = "2020-03-10" 
y = "2020-03-16"
  
a = int(x[8:10])
b = int(y[8:10])
  
if a > b:
    m = a - b
    t = b
  
else:
    m = b - a
    t = a
print(t)
  
low_price = ""
url_final = 'https://paytm.com/flights'
data = {}
  
for i in range(t, t + m+1):
    url = 'https://paytm.com/flights/flightSearch/BBI-\
    Bhubaneshwar/DEL-Delhi/1/0/0/E/2020-03-'+str(i)
      
    # Locations can be changed on 
    # the above statement
    print(url)
      
    date = "2019-12-" + str(i)
      
    # enables the script to run properly without 
    # opening the chrome browser.
    chrome_options = Options()
    chrome_options.add_argument("--disable-gpu")
      
  
    chrome_options.add_argument("--headless")
      
    driver = webdriver.Chrome(executable_path = '/path/to/chromedriver', 
                              options=chrome_options)
      
    driver.implicitly_wait(20)
    driver.get(url)
      
    g = driver.find_element_by_xpath("//div[@class='_2gMo']") 
    price = g.text
      
    x = price[0]
    y = price[2:5]
    z = str(x)+str(y)
    p = int(z)
    print(p)
      
    prices=[]
    if p <= 2000:
        data[date] = p
          
for i in data:
    low_price += str(i) + ": Rs." + str(data[i]) + "\n"
      
print(low_price) 
  
if len(data) != 0:
      
    dp = 2000
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.ehlo()
    server.starttls()
    server.ehlo()
      
    server.login('your_email_id','your_password')
    subject = "Flight price for BBI-DEL has fallen\
    below Rs. " + str(dp)
      
    body = "Hey Akash! \n The price of BBI-DEL on PayTm \
    has fallen down below Rs." + str(dp) + ".\n So,\
    hurry up & check: " + url_final+"\n\n\n The prices of\
    flight below Rs.2000 for the following days are\
    :\n\n" + low_price
      
    msg = f"Subject: {subject} \n\n {body}"
      
    server.sendmail(
        # email ids where you want to
        # send the notification
        'email_id_1',
        'email_id_2',
        msg
        )
      
    print("HEY,EMAIL HAS BEEN SENT SUCCESSFULLY.")
       
    server.quit()

Producción:

python-selenium

Publicación traducida automáticamente

Artículo escrito por madara_1999 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *