No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Typos

19/24
Recursos

Aportes 46

Preguntas 4

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

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

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)

El video no me carga, es solo a mi?

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

Comparto mi versión:

Bastante más simple en mi opinión 😄
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())

!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')
mi codigo: ```js 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")

super

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

class Typos(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path=r'C:/Users/Usuario/Documents/platzi/python/Clases del Curso de Introducción a Selenium con Python/chromedriver.exe')
        driver = self.driver
        driver.get('https://the-internet.herokuapp.com/')
        driver.maximize_window()
        driver.find_element(By.LINK_TEXT, 'Typos').click()

    def test_typo(self):
        self.assertTrue(self.is_correct_elements(), 'Texto no es correcto.')
        sleep(3)

    def is_correct_elements(self):
        driver = self.driver
        try:
            driver.find_element(By.XPATH, '//*[@id="content"]/div/p[1][contains(text(),"This example demonstrates a typo being introduced. It does it randomly on each page load.")]')
            driver.find_element(By.XPATH, '//*[@id="content"]/div/p[2][contains(text(),"Sometimes you\'ll see a typo, other times you won\'t.")]')
            return True
        except:
            return False


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

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

Para realizar Web Scraping con Selenium:
https://www.scrapingbee.com/blog/selenium-python/

Hola. Esta fue mi solución:
PD: Sé que no es buena práctica hacer una prueba sin assert, sin embargo lo quise hacer así

def test_typos(self):
        driver = self.driver
        text = driver.find_element(By.CSS_SELECTOR, '#content > div > p:nth-child(3)')

        tries = 1
        while text.text != "Sometimes you'll see a typo, other times you won't.":
            driver.refresh()
            text = driver.find_element(By.CSS_SELECTOR, '#content > div > p:nth-child(3)')
            tries += 1
        
        print(f"It takes {tries} tries to be good.")
import unittest
from selenium import webdriver

class Typos(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path= './chromedriver')
        driver = self.driver
        driver.get('https://the-internet.herokuapp.com/')
        driver.find_element_by_link_text('Typos').click()


    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:
            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 the typo")

    def tearDown(self):

        self.driver.close()


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

así corregí el código del ejercicio.

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

class Typos(unittest.TestCase):
    
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path= r'/mnt/c/Users/luism/OneDrive/Desktop/chromedriver.exe')
        driver = self.driver
        driver.get("Link") # Colocar link aqui
        driver.find_element_by_link_text('Typos').click()
        driver.maximize_window()

    def test_find_typo(self):
        driver = self.driver

        tries = 1
        found = False
        correct_text = "Sometimes you'll see a typo, other times you won't."

        while not found:
            paragraph_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)')
            text_to_check = paragraph_to_check.text

            if text_to_check == correct_text:
                found = True
            else:
                
                tries += 1
                driver.refresh()

        self.assertEqual(found, True)

        print(f"It took {tries} tries to find the typo")

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


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

Adjunto mi solución:

import unittest
from selenium import webdriver


class Reto4(unittest.TestCase):
    def setUp(self) -> None:
        self.driver = webdriver.Edge(executable_path="./msedgedriver.exe")
        driver = self.driver
        driver.maximize_window
        driver.get("https://the-internet.herokuapp.com")
        driver.find_element_by_link_text("Typos").click()

    def test4(self):
        driver = self.driver
        text = "Sometimes you'll see a typo, other times you won't."
        contenido = driver.find_element_by_css_selector(
            '#content > div > p:nth-child(3)').text
        recargas = 0
        while text != contenido:
            recargas += 1
            driver.refresh()
            contenido = driver.find_element_by_css_selector(
                '#content > div > p:nth-child(3)').text
        print(f'Se encontro el texto correcto con {recargas} recargas.')

    def tearDown(self) -> None:
        return super().tearDown()


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

wtf con el codigo de esta clase

code

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

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('https://the-internet.herokuapp.com/')
        driver.find_element_by_link_text('Typos').click()


    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:
            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'Its look {tries} tries to find typo')

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

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

🤠

import unittest
from selenium import webdriver

class AddRemoveElement(unittest.TestCase):

    def setUp(self) -> None:
        self.driver = webdriver.Chrome(executable_path = './chromedriver')
        driver = self.driver
        driver.get('https://the-internet.herokuapp.com/')
        driver.find_element_by_link_text('Typos').click()
        return super().setUp()

    def test_Typos(self):
        driver = self.driver
        self.assertTrue('typos'in driver.current_url)
        
        #identificando la etiqueta
        paragraph_to_check = driver.find_element_by_xpath('//*[@id="content"]/div/p[2]')
        #haciendo referencia al texto dentro de la etiqueta
        text_to_check = paragraph_to_check.text
        print(text_to_check)

        #variables de control
        tries = 1
        found = False
        correct_tex = "Sometimes you'll see a typo, other times you won't."

        while not found:
            if text_to_check == correct_tex:
                found = True
            else:
                tries += 1
                driver.refresh()
                paragraph_to_check = driver.find_element_by_xpath('//*[@id="content"]/div/p[2]')
                text_to_check = paragraph_to_check.text
        
        self.assertEqual(found, True)
        print(f"It took {tries} tries to find the typo")


    def tearDown(self) -> None:
        self.driver.close()
        return super().tearDown()

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

Hice una pequeña modificacion al codigo, para que solo quede un ciclo while

    def test_typo(self):
        driver = self.driver

        found = False
        tries = 1
        correct = "Sometimes you'll see a typo, other times you won't."

        while not found:
            text_to_check = driver.find_element_by_css_selector(
                "#content > div > p:nth-child(3)").text
            if text_to_check != correct:
                tries += 1
                driver.refresh()
            else:
                found = True
        print(f"It takes {tries} to complete")

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 texbox?

En mi caso lo hice mas corto:

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

class Typos(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome('..\chromedriver.exe')
        driver = self.driver
        driver.maximize_window()
        driver.get('https://the-internet.herokuapp.com/')
        driver.find_element_by_link_text('Typos').click()

    def test_find_typo(self):
        driver = self.driver
        correct_text = "Sometimes you'll see a typo, other times you won't."
        text_to_check = ""
        tries = 1

        while True:
            text_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)').text
            if text_to_check == correct_text:
                break
            tries += 1
            driver.refresh()
        
        print(f"Tries: {tries}")

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


if _name_ == "_main_":
    unittest.main(verbosity=2)

Si la intención del ejercicio, es solo verificar cuantos intentos le toma selenium en encontrar el texto correcto, pienso que el segundo while sobra, al igual el assert:


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.find_element_by_link_text('Typos').click()

    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

        tries = 1
        correct_text = "Sometimes you'll see a typo, other times you won't."

        while text_to_check != correct_text:
            driver.refresh()
            tries += 1
            paragraph_to_check = driver.find_element_by_xpath('//*[@id="content"]/div/p[2]')
            text_to_check = paragraph_to_check.text

        print(f"It took {tries} tries to find the typo")

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


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


También, podría colocar un límite de intentos, para evitar un loop infinito y ahí si aplicaría el assert al final.

Así quedaría el código con Assert como menciono el profesor como reto. Tiene la ‘desventaja’ de que al encontrar el error te lo marca en consola ya lo intente condicionar con Try, Except para que se autoevalue de nuevo pero queda más largo y eso nos lleva a esta implementación del video.

Pero se los dejo por si les sirve 😃

import unittest
from selenium import webdriver


class Typos(unittest.TestCase):
    #Prepara entorno de la prueba. 
    def setUp(self):
        self.driver = webdriver.Chrome('chromedriver')
        driver = self.driver
        driver.get("http://the-internet.herokuapp.com/")
        driver.find_element_by_link_text('Typos').click()



    #Casos de prueba
    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."

    
        self.assertEqual(text_to_check, correct_text)
        driver.refresh()
        found = True
        

        self.assertEqual(found, True)
        print(f"It took {tries} tries to find the tipo")
    #Finalizar
    def tearDow(self):
        self.driver.quit() #Revisar con close


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

Si entiendo bien la lógica del programa es contar las veces que se necesito refrescar para encontrar un TYPO (Un error), por lo tanto si se deben sumar intentos cuando text_to_check= =correct_text, sin embargo a mi concepto la logica de los dos while esta mal. El primer while asigna el texto y luego refresca, por lo cual vuelve y cambia sin hacer nada en el codigo y perdiendo la posibilidad de contar intentos. Ademas en el segundo while no se debe cambiar la variable found a True cuando text_to_check= =correct_text, va en contra del propósito, debe ser True cuando se encuentra el typo no cuando el texto es correcto. Adjunto les dejo mi código funcionando

import unittest
from selenium import webdriver

class NombreClase(unittest.TestCase):

    def setUp(self):
        self.driver=webdriver.Chrome(executable_path="./chromedriver.exe") 
        driver=self.driver
        driver.get("https://the-internet.herokuapp.com")
        driver.find_element_by_link_text("Typos").click()
    
    def test_find_typo(self):
        driver=self.driver      

        tries=1
        found=False
        correct_text="Sometimes you'll see a typo, other times you won't."

        
        while not found:
            #se selecciona la etiqueta del parrafo
            paragraph_to_check=driver.find_element_by_css_selector("#content > div > p:nth-child(3)")
            #se selecciona el texto de la etiqueta
            text_to_check=paragraph_to_check.text
            print(text_to_check)

            if text_to_check==correct_text:
                driver.refresh()
                tries+=1
                
            else:
                found=True

        self.assertEqual(found,True)

        print(f'tomo {tries} intentos en encontrar el typo')

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

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

Saludos chicos aqui les dejo el codigo un poco mas simplificado y mejor de leer

import unittest
from selenium import webdriver

class Typos(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox(executable_path= r'./geckodriver.exe')
        driver = self.driver
        driver.get("https://the-internet.herokuapp.com/")
        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()```

Comparto mi función de test_typos, es un poco minimalista 😁

    def test_typos(self):
        driver = self.driver
        tryes = 1
        correct_text = 'Sometimes you\'ll see a typo, other times you won\'t.' #El texto correcto
        text_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)').text #El texto que aparece en el navegador

        while text_to_check != correct_text:
            #Si el texto del navegador no es igual al texto correcto entonces refrescamos, sumamos un intento y volvemos a tomar el texto del navegador una vez haya cargado
            tryes += 1
            driver.refresh()
            text_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)').text
            sleep(1)

        self.assertEqual(text_to_check, correct_text)

        print(f'It took {tryes} tryes to catch the correct text')

Hola dejo mi aporte por acá.

	def test_account_customer(self):
		driver = self.driver
		text_to_check = driver.find_element_by_css_selector('#content > div > p:nth-child(3)').text

		print(text_to_check)
		correct_text = "Sometimes you'll see a typo, other times you won't."

		tries = 1

		while text_to_check != correct_text:
			
			text_to_check = WebDriverWait(driver,15).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#content > div > p:nth-child(3)'))).text
			driver.refresh()
			tries += 1

		print('Número de intentos {}'.format(tries))

Excelente

Mi código:

def test_typos(self):
        driver = self.driver
        
        correct_text = "Sometimes you'll see a typo, other times you won't."
        tries = 1

        while True:
            text = driver.find_element_by_css_selector("#content > div > p:nth-child(3)")
            try:
                self.assertEqual(text.text, correct_text)
                break
            except:
                tries += 1
                driver.refresh()

        print(f"Found the right text in {tries} tries")

No entendí porque el profesor pone 2 ciclos (Son necesarios?)
así me esta funcionando.

def test_find_typo(self):
    drv=self.driver
    text_to_check = drv.find_element_by_xpath('/html/body/div[2]/div/div/p[2]')
    validate_text = text_to_check.text
    correct_text = "Sometimes you'll see a typo, other times you won't."
    tries=1

    ##print(validate_text)

    while validate_text != correct_text:
        ##print("X \n")
        text_to_check = drv.find_element_by_xpath('/html/body/div[2]/div/div/p[2]')
        validate_text = text_to_check.text
        tries += 1
        drv.refresh()

    print(f"intentos {tries} >>>>>>>")

Mi version:

    def test_typo(self):
        driver = self.driver
        correct_text = "Sometimes you'll see a typo, other times you won't."

        tries = 1
        found = False

        paragraph = driver.find_element_by_css_selector('#content > div > p:nth-child(3)')
        text_to_check = paragraph.text

        # make sure the text_to_check is wrong
        while text_to_check == correct_text:
            paragraph = driver.find_element_by_css_selector('#content > div > p:nth-child(3)')
            text_to_check = paragraph.text
            driver.refresh()

        while not found:
            if text_to_check == correct_text:
                found = True
            else:
                tries += 1
                driver.refresh()
                paragraph = driver.find_element_by_css_selector('#content > div > p:nth-child(3)')
                text_to_check = paragraph.text
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
        
        tries=0
        found=False
        correct_text="Sometimes you'll see a typo, other times you won't."
        

        while not found:
            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
            if text_to_check==correct_text:
                #driver.refresh()
                found=True
        self.assertEqual(found,True)
        print(f"{tries} intentos")```
import unittest
from selenium import webdriver


class typos(unittest.TestCase):
    
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path='./chromedriver')
        driver= self.driver
        driver.get("https://the-internet.herokuapp.com/")
        driver.find_element_by_link_text('Typos').click()
        
    
    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
        
        tries=0
        found=False
        correct_text="Sometimes you'll see a typo, other times you won't."
        

        while not found:
            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
            if text_to_check==correct_text:
                #driver.refresh()
                found=True
        self.assertEqual(found,True)
        print(f"{tries} intentos")    
        
        
        
    def tearDown(self):
        self.driver.quit()
    

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

Un pequeño error (creo): El contador de tries solo sumará un conteo si el texto a chequear es igual al correcto, es decir que por error siempre mostrará que tomó 2 intentos

No entiendo porque el profesor está usando una url incorrecta y le funciona. Bueno, la url correcta es https://the-internet.herokuapp.com/typos

creo que el script esta completo solo con el primer while y agregar la adicion de los intentos en este

Hola, cambie el conteo al primer while y el refresh lo coloque al principio y lo elimine el segundo while:

import unittest
from selenium import webdriver
from time import sleep

class Typos(unittest.TestCase):
    

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path = r"G:\\PLATZI\\PROYECTOS_PLATZI\\Curso de Introducción a Selenium\\chromedriver.exe")
        driver = self.driver
        driver.implicitly_wait(15)
        driver.maximize_window()
        driver.get('https://the-internet.herokuapp.com')
        driver.find_element_by_link_text('Typos').click()
        
    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:
                found = True

        self.assertEqual(found, True)

        print(f'It took {tries} tries to find the typo')

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

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

Me estoy volviendo fan de Selenium. Muchas gracias Héctor.