You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
1 Hrs
11 Min
50 Seg

Manejar alert y pop-up

12/24
Resources

Contributions 42

Questions 7

Sort by:

Want to see more contributions, questions and answers from the community?

Si a alguno le sale este error “AttributeError: ‘WebDriver’ object has no attribute 'switch_to_alert” como a mí, la solución es esta:

#Reemplazar esto
alert = driver.switch_to_alert()

#Por esto
alert = driver.switch_to.alert 
import unittest
from selenium import webdriver

class CompareProducts(unittest.TestCase):

	def setUp(self):
		self.driver = webdriver.Chrome(executable_path = r'.\chromedriver.exe')
		driver = self.driver
		driver.implicitly_wait(30)
		driver.maximize_window()
		driver.get("http://demo-store.seleniumacademy.com/")
	
	def test_compare_products_removal_alert(self):
		driver = self.driver
		search_field = driver.find_element_by_name('q')
		#como buena práctica se recomienda limpiar los campos
		search_field.clear()


		search_field.send_keys('tee')
		search_field.submit()

		driver.find_element_by_class_name('link-compare').click()
		driver.find_element_by_link_text('Clear All').click()
		
		#creamos una variable para interactuar con el pop-up
		alert = driver.switch_to_alert()
		#vamos a extraer el texto que muestra
		alert_text = alert.text

		#vamos a verificar el texto de la alerta
		self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)
		
		alert.accept()

	def tearDown(self):
		self.driver.implicitly_wait(3)
		self.driver.close()

if __name__ == "__main__":
	unittest.main(verbosity = 2)

Hola mi IDE (PyCharm) Me muestra que la función ‘switch_to_alert()’ está deprecada. Como alternativa, me dice que use ‘switch_to.alert’. Es una advertencia funciona aún de las dos formas.

Adicionalmente, estoy usando el driver para firefox y me salía un error en la línea 21. 'could not be scrolled into view'.
Busqué en stackoverflow y tuve que hacer un cambio, agregando librerías adicionales para hacer funcionar dicha línea.
Línea 21:

WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CLASS_NAME, "link-compare"))).click()

Librerias:

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

Al ejecutar el código del ejemplo me arrojaba el error:

AttributeError: 'WebDriver' object has no attribute 'switch_to_alert'

Lo solucioné reemplazando

alert = driver.switch_to_alert()

por 

alert = driver.switch_to.alert

Saludos.

Codigo fuenre

Cambie este codigo 
#alert = driver.switch_to_alert()
Por    
alert = driver.switch_to.alert 
import unittest
from pyunitreport import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.support import select
from selenium.webdriver.support.ui import Select


class Alerts(unittest.TestCase):
    
    def setUp(self):
        self.driver = webdriver.Chrome("D:\webdriver-chrome/chromedriver.exe")
        driver = self.driver
        driver.implicitly_wait(50)
        driver.maximize_window()
        driver.get('http://demo-store.seleniumacademy.com/')

    def test_compare_products_removal_alert(self):
        driver = self.driver
        search_field = driver.find_element_by_name('q')
        search_field.clear()

        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element_by_class_name('link-compare').click()
        driver.find_element_by_link_text('Clear All').click()

    #alert = driver.switch_to_alert()
        alert = driver.switch_to.alert 
        alert_text = alert.text

        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)
        alert.accept
        


    def tearDown(self):
        self.driver.quit()


if __name__ == "__main__":
    unittest.main(verbosity=2,testRunner=HTMLTestRunner(output="reportes", report_name="prueba_asssert"))


Las cosas han cambiado un poquito para el día de hoy 8 de Agosto, 2022. Así que les comparto mi código por si les sirve de guía:

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

class CompareProducts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
        driver = self.driver
        driver.implicitly_wait(30)
        driver.maximize_window()
        driver.get("NoAceptaElWebsite")

    def test_compare_products_removal_alert(self):
        driver = self.driver
        search_field = driver.find_element(By.NAME, 'q')
        search_field.clear()
        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element(By.CLASS_NAME, 'link-compare').click()
        driver.find_element(By.LINK_TEXT, 'Clear All').click()

        alert = driver.switch_to.alert
        alert_text = alert.text
        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)
        alert.accept()

    def tearDown(self):
        self.driver.implicitly_wait(3)
        self.driver.close()


if __name__ == "__main__":
	unittest.main(verbosity = 2)

#HappyCoding

No conocía la funcionalidad de swich_to_alert en fin selemiun tiene infinidad de cosas super útiles, un buen debug para ver que es lo que hace o en donde falla es import pdb; pdb.set_trace(), ¿se puede hacer swich al sistema de ficheros para seccionar un archivo?

Para los que quieran elaborar reportes en Python 3.9.13 con Selenium 4.4.3 aqui el codigo.

import unittest
from selenium import webdriver
from pyunitreport import HTMLTestRunner
from selenium.webdriver.common.by import By


class Popups(unittest.TestCase):

	@classmethod
	def setUpClass(cls):
		cls.driver = webdriver.Chrome(executable_path = 'chromedriver.exe')
		cls.driver.get('http://demo-store.seleniumacademy.com/')
		cls.driver.maximize_window()
		cls.driver.implicitly_wait(15)

	def test_compare_products_removal_alert(self):

		search_field = self.driver.find_element(By.NAME, 'q')
		search_field.clear()
		search_field.send_keys('tee')
		search_field.submit()

		self.driver.find_element(By.CLASS_NAME, 'link-compare').click()
		self.driver.find_element(By.LINK_TEXT, 'Clear All').click()

		alert = self.driver.switch_to.alert
		
		alert_text = alert.text

		self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)

		alert.accept()	

	@classmethod
	def tearDownClass(cls):
		cls.driver.quit()

if __name__ == "__main__":
	   unittest.main(verbosity = 2, 
            testRunner = HTMLTestRunner(output = 'reportes', report_name = 'popup-report'))

Son muy interesantes estas funcionalidades

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

class CompareProducts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(service=Service('./chromedriver'))
        driver = self.driver
        driver.implicitly_wait(30)
        driver.maximize_window()
        driver.get('http://demo-store.seleniumacademy.com/')
    
    def test_compare(self):
        driver = self.driver
        search_field = driver.find_element(By.NAME, 'q')
        search_field.clear()

        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element(By.CLASS_NAME, 'link-compare').click()
        
        driver.find_element(By.LINK_TEXT, 'Clear All').click()

        # Change Focus of browser to alert
        alert = driver.switch_to.alert
        alert_text = alert.text

        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)
        alert.accept()

    def tearDown(self):
        self.driver.implicitly_wait(3)
        self.driver.close()

if __name__ == '__main__':
    unittest.main(verbosity = 2)

Un saludo a todos comparto como solucione el error de;
alert = driver.switch_to_alert()
alert_text = alert.text()

<
# ALERTA
        # Para interactuar con el alert, haremos un cambio asignado dentro de una variable
        # con lo cual el cursor dentro del navegador se centrará en el 'alert' :
        alert = driver.switch_to.alert
        # Extraeremos el texto de la alerta y lo almacenaremos dentro de un variable:
        alert_text = alert.text
        print('ALERTA !!!:', '/n', alert_text)> 

Amigos les dejo el codigo, de la clase estoy utilizando “FireFox” por que en Google chrome aveces me bloquea el acceso la pagina, aqui esta el codigo de la clase con comentarios explicados.

import unittest
from selenium import webdriver

class CompareProducts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox(executable_path= r'./geckodriver.exe')
        driver = self.driver
        driver.implicitly_wait(3)
        driver.maximize_window()
        driver.get('https://demo-store.seleniumacademy.com/')

    def test_compare_products_with_alert(self):
        driver = self.driver
        search_field = driver.find_element_by_name('q') #Buscar cuadro de busqueda
        search_field.clear() #Limpiar texto

        #Ingresar la busqueda
        search_field.send_keys('tee')
        #search_field = driver.find_elements_by_class_name('button').click()
        search_field = driver.find_element_by_xpath('/html/body/div/div[2]/header/div/div[4]/form/div[1]/button').click()
        #search_field.submit()#Enviar

        #Buscar elemento agregar a lista de comparacion
        driver.find_element_by_class_name('link-compare').click()

        #Buscar elemento para eliminar el enlace de la lista
        driver.find_element_by_link_text('Clear All').click()

        #Interaccion con elemento alert
        alert = driver.switch_to_alert() #Cambiar el foco o el cursor al elemento alert
        alert_text = alert.text#Extraer el texto, para compararlo

        #assert de comparacion del texto para decidir la accion

        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text) #Comparacion

        #Click en el boton aceptar

        alert.accept()

    def tearDown(self):
        driver = self.driver
        driver.close()

if __name__ == "__main__":
    unittest.main(verbosity= 2)

Hay un problema al usar el alert asi:

alert = driver.switch_to_alert()

solo hay que cambiarlo por

alert = driver.switch_to.alert

A mi me funcionó sin los paréntesis del alert():


    def test_compare_products_removal_alert(self):
        driver = self.driver

        search_field = driver.find_element_by_name('q')
        search_field.clear()
        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element_by_class_name('link-compare').click()

        driver.find_element_by_link_text('Clear All').click()

        alerta = driver.switch_to.alert

        alert_text = alerta.text

        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)

        alerta.accept()

        time.sleep(5)

    def tearDown(self):
        self.driver.quit()

Ya que la clase ‘link-compare’ se repite en todos los items resultados de ‘tee’, ¿cómo hace Selenium para reconocer que queríamos seleccionar el primero? o al usar la función ‘find_element_by_class_name()’ siempre se trae el primer elemento que se encuentre en el HTML y tenga este nombre de clase?

esto cada vez me sorprende

Unos de los cambios mas importantes:

alert = driver.switch_to_alert()  #Antes
alert = driver.switch_to.alert   #Ahora
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from pyunitreport import HTMLTestRunner
class CompareProducts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
        driver = self.driver
        driver.implicitly_wait(30)
        driver.maximize_window()
        driver.get("Link URL")

    def test_compare_products_removal_alert(self):
        driver = self.driver
        search_field = driver.find_element(By.NAME, 'q')
        search_field.clear()
        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element(By.CLASS_NAME, 'link-compare').click()
        driver.find_element(By.LINK_TEXT, 'Clear All').click()

        alert = driver.switch_to.alert
        alert_text = alert.text
        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)
        alert.accept()

    def tearDown(self):
        self.driver.implicitly_wait(3)
        self.driver.close()


if __name__ == "__main__":
	 unittest.main(verbosity = 2, testRunner = HTMLTestRunner(output = 'reports', report_name = 'report_alerts'))

Hola a toda la comunidad de platzi.
En mi caso tuve un error muy repetido en lo que seria |

alert = driver.switch_to_alert()

#Esto me mostraba un error y decia "object is not callable"
alert = driver.switch_to.alert

#El cambio que realice

Sin embargo la pueba se realizaba muy rapido y no supe como integrar los tiempos de espera.

La solucion a esto ultimo fue agregar un paso extra (ejemplo ir al landing page) de esta forma me pude dar cuenta que la accion de acerptar el pop up se realizaba correctamente.

los funciones que uno puede realizar con selenium y Python son sorprendentes

Un buen debug para ver que es lo que hace o en donde falla es:
import pdb; pdb.set_trace()

Quiza alguno le falle la prueba en el switch to alert
Como en mi caso, lo solucione con

alert = driver.switch_to.alert

en lugar de guion bajo necesite un punto

Muy buena clase. La verdad es que se aprende lindo. Sobre todo con los aportes de los demás compañeros.

En caso de que no sea un Alert sino una ventana emergente, como hago para cambiar el foco hacia la nueva ventana??

Estupenda clase instructor Héctor, no conocía como podíamos seleccionar los pop-ups o ventanas emergentes al momento de evaluar una aplicación, ahora lo tendré en cuenta cuando vaya a estar haciendo pruebas.

Hola, en caso de que no sea un alert, si no más bien un modal, Lo que debería hacer es validar si está visible para nosotros y depues interactuar con el formulario que esté dentro de ese modal

hola, consulta como accedo a los elementos de una ventana modal, el find\_element no encuentra nada

Propiedades de la clase WebDriver actualizadas para alert y pop-up

Propiedades de la clase WebDriver

Propiedad/Atributo Descripción Ejemplo
current_url Obtiene la URL del sitio en la que se encuentra el navegador driver.get_url
current_window_handle Obtiene la referencia que identifica a la ventana activa en ese momento driver.current_window_handle
name Obtiene el nombre del navegador subyacente para la instancia activa driver. name
orientation Obtiene la orientación actual del dispositivo móvil driver.orientation
page_source Obtiene el código fuente de disponible del sitio web driver.page_source
title Obtiene el valor de la etiqueta <title> del sitio web driver.title
accept() Aceptar el mensaje enviado por el alert. alert.accept()
dismiss() Equivalente de accept() pero rechaza alert.dismiss()
send_keys(values) Simula escribir en un elemento alert.send_keys(”Hola Mundo”)
switch_to_alert() Cambia el foco al objeto alert alert = driver.switch_to_alert()

Ayuda llevo 3 clases atoradas con el mismo problema y por mas que busco la respuesta en los aportes no la encuentro, me ha salido este error en los ultimos ejercicios:

ERROR: test_compare_products_removal_alert (main.CompareProducts)

Traceback (most recent call last):
File “/home/carlosvg/Documents/platzi_programacion_desarrollo_web/introduccion_selenium_python/venv/selenium/alert.py”, line 15, in test_compare_products_removal_alert
search_field = driver.find_element_by_name(‘q’)
AttributeError: ‘WebDriver’ object has no attribute ‘find_element_by_name’

Comparto la función de test con los cambios de alert que mencionan en los aportes y los cambios en find_element

def test_compare_products_removal_alert(self):
        driver = self.driver
        # Barra de busqueda
        search_field = driver.find_element('name', 'q')
        search_field.clear()
        
        # Busqueda y envio
        search_field.send_keys('tee')
        search_field.submit()
        
        # Añade un elemento y limpia el campo de comparación
        driver.find_element('class name', 'link-compare').click()
        driver.find_element('link text', 'Clear All').click()
        
        # Cambia al alert y toma el texto del mismo
        alert = driver.switch_to.alert
        alert_text = alert.text

        # Verifica el texto y acepta el alert
        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)
        alert.accept()

Me apareció el mismo warning. Pero cambie a driver.switch_to.alert tal como indica y todo me funcionó perfectamente, sin necesidad de importar más librerias.

Me está gustando mucho el curso!!

import unittest
from pyunitreport import HTMLTestRunner
from selenium import webdriver

class CompareProducts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path='./chromedriver')
        driver = self.driver
        driver.implicitly_wait(30)
        driver.maximize_window()
        driver.get('http://demo-store.seleniumacademy.com/')

    def test_compare_products_removal_alert(self):
        driver = self.driver
        search_field = driver.find_element_by_name('q')
        search_field.clear()
        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element_by_class_name('link-compare').click()
        driver.find_element_by_link_text('Clear All').click()

        alert = driver.switch_to_alert()
        alert_text = alert.text

        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text)

        alert.accept()



if __name__ == '__main__':
    unittest.main(verbosity=2, testRunner= HTMLTestRunner(output= 'reports', report_name= 'hello-world-report'))

Hola les comparto mis anotaciones 😄

Selenium Notion

Hola, tengo una duda, estoy haciendo un script que tiene que ir cambiando entre distintos frames, por lo que uso "switch_to.frame" y "switch_to.default_content" con regularidad, el problema está en que al utilizar "switch_to.alert" y luego querer cambiar a algún otro frame Python tira todo tipo de errores distintos, ¿hay alguna solución para eso?

¿que plugin usas en Visual Studio code para que te complete la sintaxis así? Incluso veo que te muestra un poco de documentación de cada método conforme vas escribiendo.

Para manejar popups, tenemos que decirle al navegador que cambie el focus a este último. con el método, switch_to_alert en caso de que sea un alert.

Para los popups no necesitamos importar nada más que el módulo webdriver from selenium.

Los popup o alerts son ventanas adicionales que aparecen y que también podemos manejar con Selenium.

Hola, digamos que tenemos lo siguiente: estoy creando un perfil y para subir mi foto le doy click al boton ‘subir’ y me arroja una ventana parecida al explorador de archivos de Windows, para buscar mi archivo de imagen. ¿Como se puede tratar en ese caso?

muchas gracias! excelente clase

Como puedo activar las opciones de auto completado de comando? como los que salen en el minuto 3:38

También me doy cuenta que en la dirección del archivo mi editor llega hasta alerts.py, igual uso VScode.

Me pasa lo mismo con comandos mas generales, como por ejemplo “pass”, no me aparece para auto completar.

Implementado y funcionando. Se cambió la función driver.switch_to_alert() por driver.switch_to.alert que estaba Deprectae

import unittest
from selenium import webdriver
from api_data_mock import ApiDataMock
from selenium.webdriver.support.ui import Select # Modulo para poder seleccionar del dropdown

class CompareProducts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path = r'./chromedriver.exe')
        driver = self.driver
        driver.implicitly_wait(30)
        driver.maximize_window()
        driver.get('http://demo-store.seleniumacademy.com/')

    def test_compare_products_removal_alert(self):
        driver = self.driver
        search_field = driver.find_element_by_name('q')
        #Borrar lo que hay en la barra de busqueda
        search_field.clear()
        
        search_field.send_keys('tee')
        search_field.submit()

        driver.find_element_by_class_name('link-compare').click()
        driver.find_element_by_link_text('Clear All').click()

        #Cambiar el foco al alert
        # alert = driver.switch_to_alert()
        alert =driver.switch_to.alert
        
        alert_text = alert.text
        #Validamos el mensaje del texto
        self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert.text)
        #Simular el click en aceptar
        alert.accept()

       

    def tearDown(self):
        self.driver.implicitly_wait(5)
        self.driver.close()


if __name__ == '__main__':
    unittest.main(verbosity=2)