Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Selección de elementos

13/30
Recursos

Aportes 77

Preguntas 15

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Adjunto mi codigo para que lo puedan mejorar o darme un feedback, Animo todo se puede

salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
salida

llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
llegada

duracion = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
formatear = duracion.replace('PT', '')
formatear

Ya no se usa find_elements_by_xpath.
Ahora debes hacer esto:

from selenium.webdriver.common.by import By
vuelos = driver.find_elements(By.XPATH,'xpath_expression')

Si ha ustedes no les sale ningún viaje cuando usan el Chrome con Python pero OH mágicamente usando Chrome normal si salen viajes…
Es porque Latam ha dectectado que estás usando selenium y no quiere dejarte ver sus viajes.
¿Cómo solucionar eso?
Añade este código después de options:

options.add_argument('--disable-blink-features=AutomationControlled')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

El código del reto:

print('Hora de salida:', vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime'))
print('Hora de llegada:', vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime'))
print('Duracion:', vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime').replace('PT', '').lower())

Resultado:

¡Resolución del reto!

# Hora de llegada
arrival_hour = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
arrival_hour

# Duración del vuelo
duration = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
duration

A falta de vuelos en Latam, estoy haciendo esta seccion con Aeromexico, les comparto la manera en la que lo implemente

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time


# Abrir navegador
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
driver = webdriver.Chrome(executable_path="./drivers/chromedriver.exe", options=options)
driver.get('https://aeromexico.com/es-mx/reserva/opciones?itinerary=MEX_JFK_2020-12-03.JFK_MEX_2020-12-31&leg=1&travelers=A1_C0_I0_PH0_PC0')

time.sleep(7)

# Obtener vuelos
# // -> indica que se va a buscar en todo el arbol de la pagina
vuelos = driver.find_elements_by_xpath('//button[@class="FlightOptionsFlightInfo-btnWrapper"]')
vuelo = vuelos[0]

# Del primer vuelo obtenemos hora salida y hora llegada
# . -> Indica que solo se va a buscar en esa seccion para abajo
time = vuelo.find_elements_by_xpath('.//div[@class="FlightOptionsTimeline-time"]')
departure_time = time[0].text
arrive_time = time[1].text

# Obtenemos la duracion del vuelo
duration_time = vuelo.find_elements_by_xpath('.//p[@class="FlightOptionsFlightInfoSummary-summary"]/span')
estimate_time = duration_time[1].text

print(f'Salida {departure_time}, Llegada {arrive_time}, tiempo de vuelo {estimate_time} ')
driver.close()

Pesimo curso muchos problemas para realizar el codigo aparte que ya esta desactualizado nunca explico como extraer texto de nodos y cosas basicas que selenium no puede leer directamente de xpath

Alli se hizo lo que se pudo

from time import sleep
import requests as req
from selenium import webdriver as wd
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By


URL = "https://connect.avianca.com/flights/CLO/NAP/2022-05-02/2022-09-30/1-adults?res=CO&lang=ES&utm_source=avianca"
wp_url = "https://chat.whatsapp.com/GRYhS6aPodA8vZNwOtcnbb"
XPATH_FLIGHTS = "//*/li[@class='Itinerary']"
PRICE = ".//*/div[@class='Itinerary__price ItineraryPrice__price']"
INFO_TO = ".//*/div[@class='ItineraryMain__cell ItineraryMain__cell--time Itinerary__mainCell ItineraryMain__cell--outboundDeparture Itinerary__mainCell--outboundDeparture']"
INFO_LD ="//*/div[@class='ItineraryMain__cell ItineraryMain__cell--time Itinerary__mainCell ItineraryMain__cell--outboundArrival Itinerary__mainCell--outboundArrival']"
FOX = Service(r"C:\Drivers\firefox\geckodriver.exe")



def run_firefox():
    t = 0
    r_url =req.get(URL)
    if r_url.status_code == 200:
        try:       
            opt = wd.FirefoxOptions()
            firefox = wd.Firefox(service=FOX, options=opt)
            firefox.get(URL)
            sleep(5)
            flights = firefox.find_elements(By.XPATH, value=XPATH_FLIGHTS)
            sleep(5)
            for i in flights:
                price = i.find_element(By.XPATH, value=PRICE).get_attribute("outerText")
                info_to = i.find_element(By.XPATH, value=INFO_TO).get_attribute("innerText")
                info_ld = i.find_element(By.XPATH, value=INFO_LD).get_attribute("innerText")
                print(f"El vuelo sale a las {info_to} y llega a las {info_ld} con un valor de: {price}")
               
        except Exception as erre:
            print("Error en run_firefox: " , "\n", erre)




if __name__ == "__main__":
    run_firefox()

En las ultimas librerias de selenium es posible usar la sintaxis que se muestra en la clase pero no es lo recomendado, ya que para tener una sentencia correcta y entendible se tendrá que hacer lo siguiente.
1-) Importar la nueva libreria
form ‘selenium. webdriver. common. by’ import By
(sin espacios)
2-) remplazar la sentencia de la siguiente manera:
flights=driver.find_elements(By.XPATH,’ //li[@class=“flight”]’)

Más información link

qué pasa si la variable **vuelos ** entrega un resultado vacío y es tipo lista ?

Qué estoy haciendo mal ?

Aporto solución válida para Mayo 2022. Tener en cuenta que tuve que sacarle al arrival time un text hijo que decía “+1”. Me costó un montón encontrar la solución a eso, ya que con selenium no es tan fácil. Finalmente lo logré. Además tener en cuenta que uso “contains” para no poner los “id” de las clases, que seguramente van cambiando con el tiempo:

for flight in flights:
    departure_time = flight.find_element(By.XPATH, './/div[contains(@class, "flight-information")][1]/span').text
    flight_duration = flight.find_element(By.XPATH, './/div[contains(@class, "flight-duration")]/span[2]').text
    arrival_time_el = flight.find_element(By.XPATH, './/div[contains(@class, "flight-information")][2]/span')
    arrival_time_child = arrival_time_el.find_element(By.XPATH, './*').text
    arrival_time = arrival_time_el.text.replace(arrival_time_child, '')
    print(f'Departure time: {departure_time}. Flight duration: {flight_duration}. Arrival time: {arrival_time}')

¿No te sale un botón de “Cambiar al sitio de Latam país de destino”?
Aquí una forma para que Selenium automaticamente haga click en "Continuar en LATAM país"
Primero, después de:

from selenium import webdriver

Importar esto:

from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Luego, después de:

driver.get(url)

Poner:

by_locator = (By.XPATH,'//*[@id="country-suggestion-body-reject-change"]/span')
boton = WebDriverWait(driver, 5).until(EC.visibility_of_element_located(by_locator))
ActionChains(driver).click(element).perform()

Solución al reto.

Aquí tomé en cuanta todos los vuelos:

for vuelo in vuelos:
    schedule = vuelo.find_elements_by_xpath('.//div[@class="sc-izvnbC eqFECQ flight-information"]/span[@class="sc-gMcBNU gwIRwm"]')
    duration = vuelo.find_element_by_xpath('.//span[@class="sc-iLVFha jrpeUd"]')
    print(f'Salida a: {schedule[0].text}, llega a:  {schedule[1].text} y dura: {duration.text}')

Esto funciona para el 6 de diciembre del 2021

Mi función para obtener información acerca de cada vuelo:

def obtener_info_vuelo(vuelo):
    hora_salida, hora_llegada = vuelo.find_elements_by_xpath('.//span[contains(@class, "dFRJGh")]')
    duracion = vuelo.find_element_by_xpath('.//span[contains(@class, "ZOLOQ")]')
    precio = vuelo.find_element_by_xpath('.//span[contains(@class, "displayAmount")]')
    return (hora_salida.text, hora_llegada.text, duracion.text, precio.get_attribute('aria-label'))

A Julio de 2021 la solución, para todos los vuelos, es esta:

for flight in flights:
    flight_info = flight.find_elements_by_xpath('.//div[@class="sc-hAXbOi jocxib flight-information"]')
    departure = flight_info[0].find_element_by_xpath('.//span[@class="sc-cfWELz iIRsqM"]').text
    arrival = flight_info[1].find_element_by_xpath('.//span[@class="sc-cfWELz iIRsqM"]').text
    flight_time = flight.find_element_by_xpath('.//span[@class="sc-hCaUpS cTjSBD"]').text
    arrival = arrival.replace('\n', '')
    print(f'Salida:{departure} Llegada:{arrival} Duración:{flight_time}')

La salida:
Salida:13:00 Llegada:13:55+1 Duración:17 h 55 min
Salida:17:56 Llegada:17:10+1 Duración:16 h 14 min
Salida:21:15 Llegada:14:10+1 Duración:9 h 55 min

Algo a destacar es que los elementos que contienen las horas de salida y llegada tienen los mismos atributos de class, así que lo que tuve que hacer es obtener esa lista de dos elementos y acceder luego a uno y otro para extraer la información.

Si quieren realizarlo en google colabs

!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--incognito')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
driver.get(url)

#Obteber Vuelos
vuelos = driver.find_elements_by_xpath('//li[@class="ng-star-inserted"]')
vuelos

#Obtener el primer vuelo
vuelo = vuelos[0]
vuelo

# Hora de Salida
vuelo.find_element_by_xpath('//span[contains(@class,"hour departure")]').text
# contains  sirve para obtener el elemento cuando tienes varios parametro en el atributo class
#Hora de llegada
vuelo.find_element_by_xpath('//span[contains(@class,"hour arrival")]').text
#Duracion del Vuelo
vuelo.find_element_by_xpath('//span[@class="time"]').text

Hola. Comparto mi código para obtener el día de vuelo, horarios y precios de ese día.
Utilice Xpath y CSS Selectors, para más info: https://selenium-python.readthedocs.io/locating-elements.html

vuelos = driver.find_elements_by_xpath('//li[@class="flight"]')
prices = driver.find_elements_by_css_selector('li.flight span.value')
flight_days = driver.find_elements_by_css_selector('div.week-day-selector time')

for vuelo in range(len(vuelos)):
    departure = vuelos[vuelo].find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
    arrival = vuelos[vuelo].find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
    price = prices[vuelo].text
    flight_day = flight_days[0].get_attribute('datetime')
    
    print(f'Flight Day: {flight_day}')
    print(f'Option: {vuelo}\n Departure: {departure} \n Arrival: {arrival} \n Price: ${price} COP')```

Resultado:

- Flight Day: 2021-03-02
Option: 0
 Departure: 18:22 
 Arrival: 17:05 
 Price: $1.277.200 COP
Flight Day: 2021-03-02
Option: 1
 Departure: 12:51 
 Arrival: 17:05 
 Price: $1.277.200 COP
Flight Day: 2021-03-02
Option: 2
 Departure: 22:55 
 Arrival: 14:55 
 Price: $1.475.860 COP

Mi solucion:

Hora de llegada

vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')

Duración del vuelo

vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text

Mas informacion acerca de com crear tu propio xpath
aqui

Xpath

Les dejo un link de introducción a Xpath

Solución al reto, Código y Output:

Mi aporte es similar al reto pero buscando gráficas en mercado libre

from time import sleep
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, StaleElementReferenceException, \
    NoSuchElementException


def scrape(driver, lista_title_value):
    nvidia_graficas = driver.find_elements_by_xpath('//li[@class="ui-search-layout__item"]')

    for nvidia in nvidia_graficas:
        value = nvidia.find_element_by_xpath('.//span[@class="price-tag-fraction"]')
        title = nvidia.find_element_by_xpath('.//div[@class="ui-search-item__group ui-search-item__group--title"]/a')
        ti_va=title.get_attribute("title"),value.text
        lista_title_value.append(ti_va)


def cokkie_banner(driver):
    try:

        banner=driver.find_element_by_id('cookieDisclaimerButton')
        if banner.is_enabled() and banner.is_displayed():
            banner.click()
        else:
            raise NoSuchElementException

    except NoSuchElementException as nex:
        return nex

def siguiente(driver):
    return driver.find_element_by_xpath('//li[@class="andes-pagination__button andes-pagination__button--next"]//span[@class="andes-pagination__arrow-title"]')

if __name__ == '__main__':
    url = 'https://listado.mercadolibre.com.co/nvidia#D[A:nvidia]'


    driver = webdriver.Chrome(executable_path='./elements/chromedriver')
    driver.maximize_window()
    driver.get(url)

    lista_title_value=[]
    contador=0
    sig_button = siguiente(driver)

    ##while sig_button.is_enabled():
    for i in range(0,2):
        try:
            cokkie_banner(driver)
            scrape(driver,lista_title_value)
            sig_button.click()
            sig_button = siguiente(driver)

        except StaleElementReferenceException as ex:
            print(ex)
            print("se putio otra vez")
        except ElementClickInterceptedException as el:
            print(el)

    for elment in lista_title_value:
        print(elment)
    print(len(lista_title_value))
    driver.quit()

En enlace al Cheatseet ya no existe. Me encontré este otro por si les es de ayuda.
Xpath cheatsheet: https://devhints.io/xpath#prefixes

A mi parecer esta es una librería algo mas completa: https://www.youtube.com/watch?v=gKT_tg87H5Y

Para los que hagan el curso en el 2022 en adelante, selenium actualizo y lo que aparece en este video ya esta obsoleto, aclaro que yo lo hice con firefox y otra aerolinea, lo que deben hacer es lo siguiente:

from time import sleep
import requests as req
from bs4 import BeautifulSoup as bs
from selenium import webdriver as wd
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By


URL = "https://connect.avianca.com/flights/CLO/NAP/2022-05-02/2022-09-30/1-adults?res=CO&lang=ES&utm_source=avianca"
wp_url = "https://chat.whatsapp.com/GRYhS6aPodA8vZNwOtcnbb"
XPATH_FLIGHTS = "//*/li[@class='Itinerary']/text()"
FOX = Service(r"C:\Drivers\firefox\geckodriver.exe")


def run_firefox():
    r_url =req.get(URL)
    if r_url.status_code == 200:
        try:       
            opt = wd.FirefoxOptions()
            opt.add_argument("--incognito")
            firefox = wd.Firefox(service=FOX, options=opt)
            firefox.get(URL)
            sleep (5)
            flights = firefox.find_elements(By.XPATH, value="//*/li[@class='Itinerary']")
            print(flights)
        except Exception as erre:
            print("Error: " , "\n", erre)


if __name__ == "__main__":
    run_firefox()

coscu

Para los que quieran usar Selenium en Google Colab:

!pip install selenium
!apt-get update 
!apt install chromium-chromedriver

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',options=options)
driver.get("https://platzi.com/home")##Aqui ingresan su url

Al seguir los pasos me sale un “DeprecationWarning”, para lo cual realice los siguientes pasos.

from selenium.webdriver.common.by import By

medicamentos = driver.find_elements(By.XPATH, '//div[@class="newShopCard"]')

En el código medicamentos = vuelos

info_fligth = vuelo.find_element(By.XPATH,'.//div[@class="sc-dPNhBE jDNrxf"]')
departure_time = info_fligth.find_element(By.XPATH,'.//div[1]/span[1]').text
arrival_time = info_fligth.find_element(By.XPATH,'.//div[3]/span[@class="sc-kkwfeq hZlYEC"]').text
fligth_time = vuelo.find_element(By.XPATH,'.//span[@class="sc-cbMPqi cikZpY"]').text


#print(info_fligth.text)

print(f'Departure time: {departure_time}\nArrival time : {arrival_time}\nFligth time : {fligth_time}')

OCTUBRE 2021 RETO:

ARRIVAL HOUR:

arrival = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
arrival

DURATION

duration = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
duration 

A la fecha del curso el sitio cambio, ya solo viene en un span como texto, con selenium lo obtendríamos de esta forma…

fligth.find_element_by_xpath('.//div[@class="sc-iFUGim fupCEn flight-information"]/span').text

El resultado sería el texto en string como el profesor concluye

pongo mi código ya que a cambiado varios tags desde la publicación del curso:

vuelos = driver.find_elements_by_xpath('//li[@class = "sc-cmIlrE fjEGlq"]')
vuelos
vuelo = vuelos[0]
vuelo
vuelo.find_element_by_xpath('.//div[@class ="sc-lnmtFM PqIYF flight-information"]/span[@class ="sc-FQuPU jARUtw"]').text

Realizamos un ruta de búsqueda, traemos los li con la clase flight

vuelos = driver.find_elements_by_xpath('//li[@class="flight"]')
vuelos
[<selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="328c6fa6-21ba-49dd-b771-0fc91d68c7cb")>,
 <selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="1970702b-335c-4609-9cb4-ae8cecd2d6ff")>,
 <selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="33821564-c4d0-40e2-aba5-6eaf663389dc")>,
 <selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="ef752759-db96-435b-9857-b0adb5e0c898")>,
 <selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="6920abfb-aa2f-4f96-8889-a312608d27f0")>,
 <selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="d75024eb-1ab8-47b8-af44-747cdbeb7dc7")>]

Tomamos un solo elemento para analizarlo

vuelo = vuelos [0]
vuelo
<selenium.webdriver.remote.webelement.WebElement (session="f0d01af0f1c79510eb9c5ec81bc44761", element="328c6fa6-21ba-49dd-b771-0fc91d68c7cb")>

Ya seleccionado el 1er elemento, vamos a buscar la hora de salida para eso hacemos una nueva ruta. Como es un único elemento una sola hora de salida entonces usamos element.

Con el punto le indicamos que va a buscar solo en este árbol del elemento seleccionado. Sino colocamos el punto buscara en todo el árbol de la pagina. Como no es un hijo directo de este vuelo colocamos // para que busque un div con la clase “departure” luego dentro de este link buscamos la hora de salida que esta en “time” pero este si es un hijo directo entonces usamos solo un /

Ya tenemos la etiqueta time, ahora usamos el método get para acceder a su atributo datetime que es donde se encuentra la hora de salida.

hora_salida = vuelo.find_element_by_xpath('//div[@class="departure"]/time').get_attribute('datetime')
hora_salida

‘08:38’

hora_llegada = vuelo.find_element_by_xpath('//div[@class="arrival"]/time').get_attribute('datetime')
hora_llegada

‘07:45’

duracion = vuelo.find_element_by_xpath('//span[@class="duration"]/time').get_attribute('datetime')
duracion

‘PT23H7M’

# Encontrar la hora de llegada y la duración del vuelo

print('Hora de llegada: ', vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime'))
print('Duración de vuelo: ', vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime').replace('PT', ''))

Ese truco no lo sabía sobre el inspector de elementos, pero me imagino que eso solo pasa en ciertas páginas no en todas.

Elementos importantes de xpath:

"//" busca en todos los hijos del elemento. "/" busca sólo en hijos directos
"." indica que la búsqueda debe empezar en ese elemento y no en el origen del árbol
Los atributos de los tags se buscan entre [] y con @

Aquí la solución 😄

# Ahora para la hora de llegada 
arrival = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
print(arrival)
# y duración del vuelo
duration = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
print(duration)
duracion = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text```

Reto:

# ...

hora_salida = vuelo.find_element_by_css_selector('.departure time')
hora_salida = hora_salida.get_attribute('datetime')
print(hora_salida)

hora_llegada = vuelo.find_element_by_css_selector('.arrival time')
hora_llegada = hora_llegada.get_attribute('datetime')
print(hora_llegada)

duracion = vuelo.find_element_by_css_selector('.duration time')
duracion = duracion.text
print(duracion)

# ...
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')

es posible ver el contenido asi como lo haciamos con bs

duracion=vuelo.find_element_by_xpath('.//span[@class="duration"]/time')
duracion.get_attribute('datetime')
print(duracion.text)

llegada=vuelo.find_element_by_xpath(’.//div[@class=“arrival”]/time’)
llegada.get_attribute(‘datetime’)
print(llegada.text)

<code>
print("Hora de llegada")
print(vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime'))
print("Duración")
print(vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')).replace('PT', '').replace('H', ':').replace('M', '')

Mi solución

# Encontrando hora de llegada
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')

# Encontrando la duración del vuelo
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text

Que ventaja tiene usar XPATH sobre los selectores de CSS?
A mi me parece que con CSS tiene una sintaxis mas corta, facil de entender y limpia en general, puede usar expresiones regulares y para los que saben de frontend ya estan familarizados.
Porque usar XPATH?, no se si tenga algo que no se nota a simple vista, como velocidad de busqueda o que se yo

vuelo = vuelos[0]
vuelo_datos = {}

vuelo_datos['salida'] = vuelo.find_element_by_css_selector('.departure > time').get_attribute('datetime')
vuelo_datos['llegada'] = vuelo.find_element_by_css_selector('.arrival > time').get_attribute('datetime')
vuelo_datos['duracion'] = vuelo.find_element_by_css_selector('.duration > time').get_attribute('datetime')
#Vamos a extraer la hora de salida 

salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
print('Salida', salida)


#Llegada
llegada =  vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
print('Llegada', llegada)
#Duracion
horas =  vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
print('Duracion', horas[2:].lower())

Super Clase💪

# Salida
vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')

# Llegada
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')

# Duración
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
hora_salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
print(f'la hora de salida es {hora_salida}')
hora_llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
print(f'la hora de llega es {hora_llegada}')
duracion_completa = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
duracion=duracion_completa[2:]
print(f'Tiempo de duración {duracion}')

Les comparto mi código, quise obtener los precios pero no pude,alguien lo ha intentado??

def Obtener_info(vuelo):
    rec_dict={}
    departure = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
    if departure:
        rec_dict['departure']=departure
    arrive = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
    if arrive:
        rec_dict['arrive']=arrive
    duration_flight = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
    duration_flight = duration_flight.replace('PT','')
    duration_flight = duration_flight.replace('H','  Horas ')
    duration_flight = duration_flight.replace('M','  Minutos ')
    duration_flight 
    if duration_flight:
        rec_dict['Duration']=duration_flight
    price =    
        
    return rec_dict 

Les comparto mi codigo:

vuelo_salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
vuelo_llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
duracion_vuelo = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text
print(f'Salida del vuelo: {vuelo_salida}')
print(f'Llegada del vuelo: {vuelo_llegada}')
print(f'Duracion del vuelo: {duracion_vuelo}')```

Comparto mi solución

hora_salida = driver.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
hora_llegada = driver.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
duration = driver.find_element_by_xpath('.//span[@class="duration"]/*').text
print('La hora de salida es {}, y hora de llegada es {}, duraccion aproximada de {}'.format(hora_salida,hora_llegada,duration))

Done
_

Reto resuelto:

Reto completo

vuelo = vuelos[0]
ida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
duracion = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
duracion = duracion.replace('PT', '').replace('H',' horas ').replace('M',' minutos')
print(f'La hora de ida es {ida}')
print(f'La hora de llegada es {llegada}')
print(f'El vuelo demorara {duracion}')
#Hora de llegada vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
 #Duracion del vuelo vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text

Done !!! 😄

vuelo.find_element_by_xpath('.//div [@class= "arrival"]/time').get_attribute('datetime') vuelo.find_element_by_xpath('.//span [@class="duration"]/time').text```
salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
print(salida)
llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
print(llegada)
tiempo_vuelo = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text
print(tiempo_vuelo)```

El primero:

# Hora de llegada
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')

Segundo:

# Duración del vuelo
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')

Muy bien hasta aquí

salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
precio = vuelo.find_element_by_xpath('//span[@class="value"]/span').text
duracion = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text

print(f'El vuelo llega  a las: {llegada}hrs || Despega a las: {salida}hrs || Dura: {duracion} || Cuesta: {precio} USD')
hour_departure = vuelo.find_element_by_xpath(".//div[@class='departure']/time").get_attribute('datetime')


hour_arrival = vuelo.find_element_by_xpath(".//div[@class='arrival']/time").get_attribute('datetime')

duration = vuelo.find_element_by_xpath(".//span[@class='duration']/time").text

Esta es la solucion a mi reto

vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').text
# De la etiqueta seleccionada para abajo hay que poner el punto
hora_salida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
hora_llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
horas_vuelo = vuelo.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[1]/div[4]/div/div[2]/section[1]/ul/li[1]/div/div/div/span/time/span[1]').text
minutos_vuelo = vuelo.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[1]/div[4]/div/div[2]/section[1]/ul/li[1]/div/div/div/span/time/span[2]').text

print(f'La hora de salida es {hora_salida}')
print(f'La hora de llegada es {hora_llegada}')
print(f'El tiempo del vuelo es de {horas_vuelo} horas con {minutos_vuelo} minutos')


La hora de salida es 01:00
La hora de llegada es 15:52
El tiempo del vuelo es de 12h horas con 52min minutos

Trabaje con el site de MercadoLibre, con los nombres de las clases y extraje toda la data:

url = "https://listado.mercadolibre.com.ve/xiaomi#D[A:xiaomi]"
driver.get(url)

items = driver.find_elements_by_class_name("ui-search-item__title")
costs = driver.find_elements_by_class_name("price-tag-fraction")

item_and_cost = {}
data = []
for i, item in enumerate(costs):
    item_and_cost["name"] = items[i].text
    item_and_cost["cost"] = costs[i].text
    data.append(item_and_cost.copy())

Logré el reto, pero aplicándolo para los vuelos de Avianca 😄 … Bogotá-Pereira (Colombia) hay 2 vuelos por día para el 4 de octubre.

ya después de practicar, obtuve la lista de salida y llegada de vuelos que me aparecieron

<
#lista para guardar los tiempos
tiempos=[] 
for vuelo in vuelos:
    departure=vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
    arrival=vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
    tiempos.append([departure,arrival])
> 

Cuando traté de hacer el ejercicio, la página de LATAM ya había cambiado su estructura un poco y por ejemplo, para encontrar la hora de salida había el siguiente tag:

<div class="sc-bJHhxl ixHzkt flight-information">

En este caso como lo que había dentro de class no era solo un elemento sino varios (en este caso 3) la búsqueda normal con el XPath no funcionó.

'/div[@class="flight-information"]'

Para que nos encuentre el elemento debemos hacer uso de unas funciones de XPath.
La forma de poder obtener ese tag correctamente sería:

'/div[contains(concat(" ", normalize-space(@class), " "), " flight-information ")]'

Espero a alguien más le sirva

Hola, por si alguien más tiene problemas con el driver de Chrome en Linux

pip install webdriver-manager
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

Esto me lo soluciono, espero que les sea de ayuda 😉

Para la duración =

duracion = primer_vuelo.find_element_by_xpath('//div[@class ="sc-fjhmcy dbJOiq flight-duration"]/span[2]').text

Para la hora de llegada este fue mi xpath

hora_llegada = primer_vuelo.find_element_by_xpath('//div[@class ="sc-hwcHae kDhKw"]//div[3]/span[@class ="sc-lnmtFM ewiHQE"]').text

importante escribir find_elements_by_xpath y no element, pues solo traerá el primer elemento

hoy 5 de Enero hice el reto con un vuelo Bogota - Santiago,
la hora de salida y llegada las pude sacar de una lista,

<options=webdriver.ChromeOptions()
options.add_argument('--incognito')
driver= webdriver.Chrome(ChromeDriverManager().install(),options=options)
driver.get(url)
vuelos=driver.find_elements_by_xpath('//li[@class="sc-fHSTwm danPdA"]')
vuelo=vuelos[0]
datos=vuelo.find_elements_by_xpath('.//span[@class="sc-lnmtFM ewiHQE"]')
duracion=vuelo.find_element_by_xpath('.//span[@class="sc-FQuPU dkpBdw"]').text
print(datos[0].text," Es la hora de Salida")
print(datos[1].text," Es la hora de Llegada")
print("la duraciones es de ",duracion)>

La duracion si es un solo elemento

les comparto la respuesta del reto
#salida
salida=vuelo.find_element_by_xpath(".//div[@class=‘departure’]/time").get_attribute(‘datetime’)

#llegada
llegada=vuelo.find_element_by_xpath(".//div[@class=‘arrival’]/time").get_attribute(‘datetime’)

#duracion
duracion=vuelo.find_element_by_xpath(".//span[@class=‘duration’]/time").get_attribute(‘datetime’)
duracion=duracion.replace(‘PT’, ‘’)

POR FAVOR A TODOS LOS COMPANEROS SI QUIEREN APRENDER POR FAVOR USAR LA URL QUE ESTA EN LA CLASE PORQUE LA WEB DE ARGENTINA ESTA MUY BIEN ESTRUCTURADA Y PODRÁN SEGUIR LA CLASE SIN PROBLEMAS, ESTA INFORMACIÓN PUEDE SER DIFERENTE EN CADA PAÍS Y PODRÍAN TENER INCONVENIENTES SOBRE TODO SI ESTÁN APRENDIENDO SALUDOS

reto

vuelo.find_element_by_xpath('.//div[@class ="sc-lnmtFM PqIYF flight-duration"]/span[@class ="sc-kEmuub URkka"]').text
vuelo.find_element_by_xpath('.//div[@class ="sc-lnmtFM PqIYF flight-information"][2]/span[@class ="sc-FQuPU jARUtw"]').text
hora_partida = vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
hora_partida

hora_llegada = vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
hora_llegada

duracion = vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')
duracion

formato = duracion.replace('PT','')
formato