Enrique Uzcategui
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
Ismael Danilo Herrera Sánchez
EstudianteGracias bro
estefany Liza
EstudianteGracias Enrique me funciono tu solución! Gran dato
Korpi delfin
Estudianteimport 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)
Fredy Mendoza Vargas
EstudianteMuchas gracias!
Cristian David Restrepo Marin
Estudiantegracias por el aporte
Steven Moreno
EstudianteHola 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
Victor Luis Landaeta Jimenez
EstudianteHola, 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!!
Junior Erny Aguayo Cuadros
EstudianteHola 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
Alan German Gutiérrez
EstudianteAl 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.
Daniel Ignacio González Cañete
Estudiantegracias, tuve el mismo error!
estefany Liza
EstudianteCodigo 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"))
Jesús Enrique Morocoima Marcano
EstudianteSuper Me Sirvio Mucho... Gracias
Jesús Enrique Morocoima Marcano
EstudianteSuper.. Gracias Por este nuevo aporte
David Diaz
EstudianteLas 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
Humberto Adrián Hernández Maldonado
EstudianteHola 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)
David Diaz
Estudianteno está mal, amigo o.o pero si te funciona tu método, bienvenido sea 😅
Royer Guerrero Pinilla
EstudianteNo 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?
Héctor Daniel Vega Quiñones
ProfesorSí, 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 ;)
Matias Gabriel Pierri
EstudianteEstoy 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'?
Alberto Coronado
Estudianteme paso casi el mismo error, fue por typo
Randhal Smith Ramirez Orozco
EstudiantePara 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'))
Jesús Velázquez Jiménez
EstudianteSon 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)
Flavio Abat Carrola Reta
EstudianteUn 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)>
Jose Antonio Rojas Ollarves
EstudianteAmigos 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)
Edward Chapula Alcaraz
EstudianteHay un problema al usar el alert asi:
alert = driver.switch_to_alert()
solo hay que cambiarlo por
alert = driver.switch_to.alert
Jorge Salinas
EstudianteGracias crack. Llevaba rato pesando que pasaba con esa parte.
David Andrés Valero Vanegas
EstudianteA 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()
Jose Antonio Rojas Ollarves
Estudiantete hace falta el entry point para poder correr la prueba
Jose Gabriel Zaragoza
EstudianteMe sucedión lo mismo, a mi me salìa ´Alert´ object is not callable, le quité los paréntesis y funcionó perfecto :)
Carlos Andres Ocampo Pabon
EstudianteYa 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?
Julio César Zaravia Paredes
Estudiante¡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!
Jhonatan David Ibarra Lavado
Estudianteesto cada vez me sorprende
Marlon Ramirez
EstudianteUnos de los cambios mas importantes:
alert = driver.switch_to_alert() #Antes alert = driver.switch_to.alert #Ahora
Wilson Gustavo Chango Sailema
Estudianteimport 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'))
Eduardo Jimenez
EstudianteHola 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.
Angel Hernandez
EstudianteHola, le metodo que hay que usar es este:
alert = driver._switch_to.alert
Bruno Marcelo Lara Sainz
Estudiantelos funciones que uno puede realizar con selenium y Python son sorprendentes