Enrique Uzcategui
EstudianteIsmael Danilo Herrera Sánchez
Estudianteestefany Liza
EstudianteKorpi delfin
EstudianteFredy Mendoza Vargas
EstudianteCristian David Restrepo Marin
EstudianteSteven Moreno
EstudianteVictor Luis Landaeta Jimenez
EstudianteJunior Erny Aguayo Cuadros
EstudianteAlan German Gutiérrez
EstudianteDaniel Ignacio González Cañete
Estudianteestefany Liza
EstudianteJesús Enrique Morocoima Marcano
EstudianteJesús Enrique Morocoima Marcano
EstudianteDavid Diaz
EstudianteHumberto Adrián Hernández Maldonado
EstudianteDavid Diaz
EstudianteRoyer Guerrero Pinilla
EstudianteHéctor Daniel Vega Quiñones
ProfesorMatias Gabriel Pierri
EstudianteAlberto Coronado
EstudianteRandhal Smith Ramirez Orozco
EstudianteJesús Velázquez Jiménez
EstudianteFlavio Abat Carrola Reta
EstudianteJose Antonio Rojas Ollarves
EstudianteEdward Chapula Alcaraz
EstudianteJorge Salinas
EstudianteDavid Andrés Valero Vanegas
EstudianteJose Antonio Rojas Ollarves
EstudianteJose Gabriel Zaragoza
EstudianteCarlos Andres Ocampo Pabon
EstudianteJulio César Zaravia Paredes
EstudianteJhonatan David Ibarra Lavado
EstudianteMarlon Ramirez
EstudianteWilson Gustavo Chango Sailema
EstudianteEduardo Jimenez
EstudianteAngel Hernandez
EstudianteBruno Marcelo Lara Sainz
EstudianteSi 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
Gracias bro
Gracias Enrique me funciono tu solución! Gran dato
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)
Muchas gracias!
gracias por el aporte
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
Hola, a mi también 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.
Saludos!!
Hola que raro, a mi me salió el mismo error en el pycharm pero solo cambie la función a switch_to.alert y trabajo sin problemas
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.
gracias, tuve el mismo error!
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"))
Super Me Sirvio Mucho... Gracias
Super.. Gracias Por este nuevo aporte
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
Hola David, esta incorrecto tu script, debes respetar la estructura del nombre de las variables (mayúsculas y minúsculas) para que no te mande errores Te comparto tu ejercicio corregido.
import unittest import time from selenium import webdriver class CompareProducts(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path = r'C:/Users/Humberto Hernandez M/Dropbox/A Mi carpeta HH/2 Desarrollos Cursos/29 Selenium/chromedriver.exe') driver = self.driver driver.implicitly_wait(30) driver.maximize_window() driver.get("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() # Cambio de focus al alert alert = driver.switch_to.alert #extraer el texto del alert alert_text = alert.text #verificar si el texto del alert es el que esperamos time.sleep(15) self.assertEqual('Are you sure you would like to remove all products from your comparison?', alert_text) # dar clic e el noton aceptar alert.accept() time.sleep(15) def tearDown(self): self.driver.implicitly_wait(3) self.driver.close() if __name__ == "__main__": unittest.main(verbosity = 2)
no está mal, amigo o.o pero si te funciona tu método, bienvenido sea 😅
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?
Sí, es posible hacer referencia a archivos para guardarlos o directorios para descargas. Estas ya son funcionalidades avanzadas de Selenium y merecen la pena otro curso ;)
Estoy teniendo un problema y no termino de entender el error que me da
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_elements_by_class_name('link-compare').click() driver.find_elements_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()
Traceback (most recent call last): File "alerts.py", line 21, in test_compare_products_removal_alert driver.find_elements_by_class_name("link-compare").click() AttributeError: 'list' object has no attribute 'click'
Me asegure de copiar exactamente igual la linea de driver.find_elements_by_class_name('link-compare').click() pero sigue dandome ese error. Que significa ¿AttributeError: 'list' object has no attribute 'click'?
me paso casi el mismo error, fue por typo
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
Gracias crack. Llevaba rato pesando que pasaba con esa parte.
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()
te hace falta el entry point para poder correr la prueba
Me sucedión lo mismo, a mi me salìa ´Alert´ object is not callable, le quité los paréntesis y funcionó perfecto :)
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?
¡Hola!
Efectivamente, el método find_element_by_class_name trae el primer elemento cuya clase coincida con la cadena de texto que has ingresado.
Puedes revisar la lógica de estos métodos en la documentación.
¡Saludos!
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.
Hola, le metodo que hay que usar es este:
alert = driver._switch_to.alert
los funciones que uno puede realizar con selenium y Python son sorprendentes