Contenido del curso
Matias Gabriel Pierri
Junior Erny Aguayo Cuadros
Jonathan Mardones Guzmán
Royer Guerrero Pinilla
Esteban parra
Royer Guerrero Pinilla
Alexis Loya García
Carlos Andres Ocampo Pabon
Juan Jacobo Arias Ramirez
Leslie Paz Ore
Rubén Cuello
Roger Christian Cansaya Olazabal
Jeyson David Vargas Crespo
Steven Moreno
Juan Zenón
Juan Antonio Pavon Carmona
julian zoto
Pablo Antipan Quiñenao
Rafael Torres Escobar
David Fernando Peláez Muñoz
fidel angel ochoa
Ediberto Enrique Coronel Villegas
Israel Yance
Israel Yance
Bruno Guillaume Hernández Villamil
Arian Racca
Jeferson Andrés Cruz Herrera
Héctor Daniel Vega Quiñones
ProfesorMario Alexander Vargas Celis
Fabian Caballero
David Higuera
Creo que hay un error en la logica al poner el tries += 1 en if text_to_check = correct_text porque solo va a sumar un intento cuando se encuentra el texto correcto.
Al correr el script varias veces la cantidad de intentos siempre da fijo el resultado 2 porque empieza en 1 y suma 1 cuando lo encuentra aunque esto tomo 5 intentos de refrescar la pagina
Yo lo deje de esta forma
while text_to_check != correct_text: paragraph_to_check = driver.find_element_by_css_selector("#content > div > p:nth- child(3)") text_to_check = paragraph_to_check.text driver.refresh() tries += 1
Lo que dices es correcto!
Es correcto lo que planteas, aunque me parece que, con el código como lo tienes, cuenta una vez demás. Lo pongo con un ejemplo para que se entienda mejor la idea, y aunque es algo sencillo, lo escribo con lujo de detalles para que los demás lo consideren al ponerlo en su código (favor, corregir si estoy mal):
Supongamos que la primera vez que el bot ingresa a la página se encuentra con un typo, y la segunda vez encuentra el texto correcto, ¿qué contaría el bot?
Lo que pasaría es que, como la primera vez encuentra un typo, el script hace text_to_check != correct_text. Lo que hace a continuación es entrar al while y redefinir text_to_check tal cual estaba, porque no han habido cambios en la página. A continuación, refrezca la página y después suma 1 a tries (tenemos entonces que tries = 2). Supusimos inicialmente que en esta ocasión, el texto sí es correcto, ¡pero aún no se actualiza text_to_check! así que el bloque while se vuelve a ejecutar y ahora sí, actualizamos text_to_check a correct_text, refrezcamos la página nuevamente y sumamos nuevamente 1 a tries, es decir, ahora tries = 3. Como text_to_check == correct_text, no se ejecuta el bloque while y nos retorna que lo hizo en 3 intentos, cuando realmente sólo fueron 2.
La solución a esto es que lo primero que haga el ciclo while sea driver.refresh():
while text_to_check != correct_text: driver.refresh() text_to_check = driver.find_element_by_css_selector("#content > div > p:nth-child(3)").text tries += 1
PD: Me di cuenta del error en la clase gracias a tu comentario, saludos :D
El video no me carga, es solo a mi?
me ocurre lo mismo, no carga el video
Yo probé en Firefox y tampoco 🤔
Al final me quedó así
import unittest from selenium import webdriver class Typos(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome( executable_path=r'C:/Users/student/driver/chromedriver.exe') driver = self.driver driver.get("...") driver.find_element_by_link_text("Typos").click() def test_find_typo(self): driver = self.driver text_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)').text tries = 1 correct_text = "Sometimes you'll see a typo, other times you won't." while text_to_check != correct_text: text_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)').text tries += 1 driver.refresh() print(f'It took {tries} tries to find the typo') def tearDown(self): self.driver.close() if __name__ == "__main__": unittest.main(verbosity = 2)
A mí también me pareció más fácil con un solo while
Le hice una modificación para quitar un ciclo while, en el lugar de los dos while lo dejé así
while not found: if text_to_check == correct_text: driver.refresh() found = True else: paragraph_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)') text_to_check = paragraph_to_check.text tries +=1 driver.refresh()
Además de cambiar el tries+=1 cuando son distintos, ya que dejandolo donde son iguales siempre daría 2 intentos
Muy bueno, gracias!
Comparto mi versión:
Bastante más simple en mi opinión :smile: Recuerden actualizar el valor de paragraph luego de refrescar la página en el bucle while, de lo contrario van a encontrar el typo, y refrescar nuevamente.
Hay un error en su logica y por lo tanto en el codigo. Les comparto el codigo final, al fin pude usar el While / Else
import unittest from selenium import webdriver class Typos(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path = r'.\chromedriver.exe') driver = self.driver driver.get('https://the-internet.herokuapp.com/') driver.maximize_window() driver.implicitly_wait(3) driver.find_element_by_link_text('Typos').click() def test_find_typo(self): driver = self.driver paragraf_to_ckeck = driver.find_element_by_css_selector('#content > div > p:nth-child(3)') text_to_check = paragraf_to_ckeck.text print(text_to_check) tries = 1 found = False correct_text = "Sometimes you'll see a typo, other times you won,t." while text_to_check != correct_text: driver.refresh() paragraf_to_ckeck = driver.find_element_by_css_selector('#content > div > p:nth-child(3)') text_to_check = paragraf_to_ckeck.text tries += 1 else: found = True self.assertEqual(found, True) print(f"It took {tries} tries to find the typo") def tearDown(self): self.driver.implicitly_wait(3) self.driver.close() if __name__ == "__main__": unittest.main(verbosity = 2)
Hola, no me carga el video, ni siquiera me deja cambiar el servidor, me aparece una X en la pantalla y no deja hacer nada, alquien me puede ayudar???
Muchas gracias.
Adicioné, comprobando que la variable contenga texto y el mismo no se encuentre vacío
self.assertTrue(isinstance(text_to_check, str) and text_to_check.strip())
Súper de acuerdo, se me hizo muy raro cuando vi el código que el profesor escribió.
self.assertTrue(text_to_check)
De esta manera no daria el mismo resultado? text_to_check es un string al pasar el valor del text en el parráfo, y a la vez se comprueba si esta vacio o no.
no reproduce el video, :(
Hola Maria! Cuando eso ocurra, puedes probar cambiar el servidor de origen en la barra del reproductor Saludos!
No se reproducen los videos a partri de "Selección de Elementos"
!Que cuso tan frustrante!, ahhh
CORREGI que tenia un 'while' demas, que el 'found' era inutil', que tambien sumaba intentos extra y que recargaba aun despues de encontrar la frase correcta, les comparto mi codigo:
def test_find_typo(self): driver = self.driver paragraph_to_check = driver.find_element_by_xpath('//*[@id="content"]/div/p[2]') text_to_check = paragraph_to_check.text print(text_to_check) tries = 1 correct_text = "Sometimes you'll see a typo, other times you won't." while text_to_check != correct_text: text_to_check = driver.find_element_by_xpath('//*[@id="content"]/div/p[2]').text sleep(2) # segundos de pausa para poder notar las vece que se recarga la pagina y contar los intentos como comprobacion manual. if text_to_check != correct_text: # este 'if' me permite sumar solo en caso de que no exista coincidencia y solo entonces recarga. driver.refresh() tries += 1 print(f"It took {tries} tries to find the typo") def tearDown(self): self.driver.implicitly_wait(3) self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2)
Este capitulo el video esta dañado, no logro verlo
Me salió un bucle infinito solo porque al correct_text no le había puesto punto al final.
Solo unas observaciones. El tries += 1 debe ser dentro del primer while, sino siempre va a salir como resultado: dos. Además el driver.refresh() debería ser antes de la asignación del text_to_check para que vuelva a asignar el valor cuando va al siguiente while.
Dejo mi código de la función
def test_find_typo(self): driver = self.driver paragraph_to_check = driver.find_element_by_css_selector("#content > div > p:nth-child(3)") text_to_check = paragraph_to_check.text print(text_to_check) tries = 1 found = False correct_text = "Sometimes you'll see a typo, other times you won't." while text_to_check != correct_text: driver.refresh() paragraph_to_check = driver.find_element_by_css_selector("#content > div > p:nth-child(3)") text_to_check = paragraph_to_check.text tries += 1 while not found: if text_to_check == correct_text: driver.refresh() found = True self.assertEqual(found, True) print(f'It took {tries} tries to find the typo')
No me quedó claro la parte donde pone los while, no entiendo como funciona esa parte, ¿Alguien podría explicarme?
Gracias.
Hola, no se si solo me pasa a mi pero me aparece un mensaje que dice "The media could not be loaded, either because the server or network failed or because the format is not supported." Solo con este video.
Hola a tod@s tengo una consulta:
¿Cómo se podría validar que en efecto, al hacer clic sobre el botón "Enable" si se habilite el text box?
Muchas gracias!!!
Una forma es utilizar una demora explícita para esperar que aparezca el elemento y luego hacer un assertion.
mi codigo:
import unittest from selenium import webdriver from pyunitreport import HTMLTestRunner from selenium.webdriver.common.by import By #from time import sleep from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Typos(unittest.TestCase): def setUp(self): chrome_driver_path = r"/chromedriver.exe" self.driver = webdriver.Chrome() driver = self.driver driver.implicitly_wait(30) driver.maximize_window() driver.get("https://the-internet.herokuapp.com/") driver.find_element(By.LINK_TEXT, "Typos").click() def test_find_typos(self): driver = self.driver paragraph_to_check = driver.find_element(By.CSS_SELECTOR, '#content > div > p:nth-child(3)') text_to_check = paragraph_to_check.text print(text_to_check) tries = 1 found = False correct_text = "Sometimes you'll see a typo, other times you won't." while text_to_check != correct_text: paragraph_to_check = driver.find_element(By.CSS_SELECTOR, '#content > div > p:nth-child(3)') text_to_check = paragraph_to_check.text driver.refresh() while not found: if text_to_check == correct_text: tries += 1 driver.refresh() found = True self.assertEqual(found, True) print(f"It took {tries} tries to find type") def tearDown(self) -> None: self.driver.close() if __name__ == "__main__": unittest.main(verbosity = 2, testRunner = HTMLTestRunner(output = "reportes", report_name = "typos_test_report")) ```import unittestfrom selenium import webdriverfrom pyunitreport import HTMLTestRunnerfrom selenium.webdriver.common.by import By#from time import sleepfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected\_conditions as EC class Typos(unittest.TestCase):   def setUp(self): chrome\_driver\_path = r"/chromedriver.exe" self.driver = webdriver.Chrome() driver = self.driver driver.implicitly\_wait(30) driver.maximize\_window() driver.get("https://the-internet.herokuapp.com/") driver.find\_element(By.LINK\_TEXT, "Typos").click()   def test\_find\_typos(self): driver = self.driver   paragraph\_to\_check = driver.find\_element(By.CSS\_SELECTOR, '#content > div > p:nth-child(3)') text\_to\_check = paragraph\_to\_check.text print(text\_to\_check)   tries = 1 found = False correct\_text = "Sometimes you'll see a typo, other times you won't."   while text\_to\_check != correct\_text: paragraph\_to\_check = driver.find\_element(By.CSS\_SELECTOR, '#content > div > p:nth-child(3)') text\_to\_check = paragraph\_to\_check.text driver.refresh()   while not found: if text\_to\_check == correct\_text: tries += 1 driver.refresh() found = True   self.assertEqual(found, True)   print(f"It took {tries} tries to find type")   def tearDown(self) -> None: self.driver.close() if \_\_name\_\_ == "\_\_main\_\_": unittest.main(verbosity = 2, testRunner = HTMLTestRunner(output = "reportes", report\_name = "typos\_test\_report"))
Les comparto mi código
import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service class Typos(unittest.TestCase): def setUp(self): s = Service('./chromedriver') self.driver = webdriver.Chrome(service=s) driver = self.driver driver.get("PAGINA WEB") excercise = driver.find_element(By.LINK_TEXT, "Typos") excercise.click() def test_find_typos(self): driver = self.driver correct_text = "Sometimes you'll see a typo, other times you won't." pharagraph_to_check = driver.find_element(By.CSS_SELECTOR, "#content > div > p:nth-child(3)") text_to_check = pharagraph_to_check.text tries = 1 while text_to_check != correct_text: driver.refresh() tries += 1 pharagraph_to_check = driver.find_element(By.CSS_SELECTOR, "#content > div > p:nth-child(3)") text_to_check = pharagraph_to_check.text print(f"It took {tries} tries to find the typo") def tearDown(self): self.driver.close() self.driver.quit() if __name__ == "__main__": unittest.main()
Opté por esta solución:
def test_typos(self): driver = self.driver correct_text = "Sometimes you'll see a typo, other times you won't." text_to_check = driver.find_element_by_css_selector("#content > div > p:nth-child(3)").text tries = 1 while text_to_check != correct_text: tries += 1 driver.refresh() text_to_check = driver.find_element_by_css_selector("#content > div > p:nth-child(3)").text print(f"It tooks {tries} tries to find the typo")