No tienes acceso a esta clase

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

No se trata de lo que quieres comprar, sino de quién quieres ser. Invierte en tu educación con el precio especial

Antes: $249

Currency
$209

Paga en 4 cuotas sin intereses

Paga en 4 cuotas sin intereses
Suscríbete

Termina en:

11 Días
18 Hrs
51 Min
57 Seg

Elementos dinámicos

17/24
Recursos

Aportes 46

Preguntas 5

Ordenar por:

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

Que buen profesor. Mis respetos. Su forma de explicar es muy clara. Lo mejor es que usa variables y todo en ingles. ❤️

Comparto mi versión de este ejercicio. Lo que hice fue usar la función find_elemets_by_tag_name para sacar todos los elementos que son ‘li’. Luego hice loop hasta que la cantidad de elementos que encontrara fueran 5.

import unittest
from selenium import webdriver
from time import  sleep

class DynamicElement(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path=r'chromedriver.exe')
        driver = self.driver
        driver.maximize_window()
        driver.implicitly_wait(10)
        driver.get('https://the-internet.herokuapp.com/')
        driver.find_element_by_link_text('Disappearing Elements').click()

    def test(self):
        driver = self.driver
        intentos = 1
        #Capturo los elementos de la lista
        elements = driver.find_elements_by_tag_name('li')

        while len(elements) < 5:
            #Si los elementos que encontré son menores a 5 recargo la pagina y vuelvo a "contar" los elementos de la lista
            print('Elementos en la lista', len(elements))
            driver.refresh()
            elements = driver.find_elements_by_tag_name('li')
            #Sumo otro intento
            intentos += 1
            #Espero 1 segundo para que poder ver cuántas veces ha recargado
            sleep(1)

        print(f'Nos tomó {intentos} intentos para capturar a Gallery')


    def tearDown(self):
        self.driver.quit()
if __name__ == '__main__':
    unittest.main(verbosity=2)
    def test_name_elements(self):
        driver = self.driver

        len_menu = 5
        tries = 0
        menu = []

        while len(menu) < len_menu:
            tries += 1
            menu = driver.find_elements_by_xpath('//*[@id="content"]/div/ul/li')
            driver.refresh()

        print(f"number of tries: {tries}")

Yo conoci selenium caundo estaba haciendo Web Scraping de paginas dinamicas…pero no imagine que tenia todo este potencial.

Este es mi aporte, lo realice pensando en que el primer caso puede ser el resultado que se necesita:

def test_name_elements(self):
    driver = self.driver

    tries = 1
    menu = driver.find_elements_by_xpath('//*[@id="content"]/div/ul/li')
    sleep(2)

    while len(menu) < 5:
      tries += 1
      driver.refresh()
      sleep(2)
      menu = driver.find_elements_by_xpath('//*[@id="content"]/div/ul/li')

    print(f'Number of tries: {tries}')```

Hay esta otra version que hice

def test_name_elements_pro(self):
        driver = self.driver
        tries = 1
        while True:
            menu = driver.find_elements_by_css_selector('.example > ul > li')
            for i in menu:
                print(i.text)
            print('--- ' * 5)
            if len(menu) < 5:
                tries += 1
                driver.refresh()
            else:
                break

        print(f"Finish in {tries} tries")```
import unittest
from selenium import webdriver
from time import sleep

class DynamicElements(unittest.TestCase):

    def setUp(self):
        self.driver= webdriver.Chrome(executable_path= "/home/yanina/Downloads/chromedriver")
        driver= self.driver
        driver.get("http://the-internet.herokuapp.com/")
        driver.find_element_by_link_text("Disappearing Elements").click()


    def test_name_elements(self):
        driver = self.driver

        options= []
        menu = 5
        tries = 1

        while len(options) < 5:
            options.clear()

            for i in range(menu):
                try:
                    option_name= driver.find_element_by_xpath(f"/html/body/div[2]/div/div/ul/li[{i+1}]/a")
                    options.append(option_name.text)
                    print(options)
                except:
                    print(f"Option number {i+1} is not found")
                    tries= tries +1
                    driver.refresh()
            
            print(f"Finished in {tries} tries")
    
    def tearDown(self):
        self.driver.close()



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

Código realizado. :D

Podrían subir los archivos de los ejemplos como en los otros cursos? Please

Hola, creo que ‘tries += 1’. Va dentro del bloque de ‘try’ en vez de ‘except’

Nuevamente, por alguna extraña razón el profe está usando la url incorrecta.
Debe ser esta: driver.get('https://the-internet.herokuapp.com/disappearing_elements')

el codigo del profesor en esta clase no me gusto para nada, se complica solito, para empezar podriamos utilizar driver.find_elementS lo cual retornaria una lista y solo mediriamos el tamaño de esta, podriamos iterar sobre cada elemento para obtener su texto sin necesidad de utilizar un indice como lo muestra el profesor

woooo, selnium y su magia jajaja

A seguir sumando experiencia.

Excelente profe, al principio fue muy abrumador todo , pero ahora esta mas claro todo.

```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 DynamicElements(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, "Disappearing Elements").click() def test_name_elements(self): driver = self.driver options = [] menu = 5 tries = 1 while len(options) < 5: options.clear() for i in range(menu): try: option_name = driver.find_element(By.XPATH, f'//*[@id="content"]/div/ul/li[{i + 1}]/a') options.append(option_name.text) print(options) except: print(f"Option number {i + 1} is NOT FOUND") tries += 1 driver.refresh() print(f"Finished in {tries} tries") def tearDown(self) -> None: self.driver.close() if __name__ == "__main__": unittest.main(verbosity = 2, testRunner = HTMLTestRunner(output = "reportes", report_name = "dynamic_elements_test_report")) ```import unittestfrom selenium import webdriverfrom pyunitreport import HTMLTestRunnerfrom 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 DynamicElements(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, "Disappearing Elements").click() def test\_name\_elements(self): driver = self.driver options = \[] menu = 5 tries = 1 while len(options) < 5: options.clear() for i in range(menu): try: option\_name = driver.find\_element(By.XPATH, f'//\*\[@id="content"]/div/ul/li\[{i + 1}]/a') options.append(option\_name.text) print(options) except: print(f"Option number {i + 1} is NOT FOUND") tries += 1 driver.refresh() print(f"Finished in {tries} tries") def tearDown(self) -> None: self.driver.close() if \_\_name\_\_ == "\_\_main\_\_": unittest.main(verbosity = 2, testRunner = HTMLTestRunner(output = "reportes", report\_name = "dynamic\_elements\_test\_report"))

Realice el codigo y agregue reporteria

import unittest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyunitreport import HTMLTestRunner
from time import sleep


class Disappearing_elements(unittest.TestCase):
    
    @classmethod
    def setUpClass(cls) -> None:
        # Configurar el WebDriver y abrir la página web
        cls.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
        driver = cls.driver
        driver.get('URL')
        driver.implicitly_wait(3)
        driver.maximize_window()
        driver.find_element(By.LINK_TEXT, 'Disappearing Elements').click()
        
   
       
    def test_name_elements(self):
        driver = self.driver
        
        options = []
        menu = 5
        tries = 1
        
        while len(options) < 5:
            options.clear()
            
            for i in range(menu):
                try:
                    option_name = driver.find_element(By.XPATH, (f"/html/body/div[2]/div/div/ul/li[{i + 1}]/a"))
                    options.append(option_name.text)   
                    print(options)
                except:
                    print(f"Option Number {i + 1} is Not FOUND")
                    tries += 1
                    driver.refresh()
                    
        print(f"Finished in {tries} tries") #Para que en python me tome la variable debo colocar la f delante
        
        
    @classmethod
    def tearDownClass(cls) -> None:
        cls.driver.quit()
            
if __name__ == "__main__":
    # Ejecutar las pruebas y generar el informe HTML
    unittest.main(verbosity=2, testRunner=HTMLTestRunner(output='reportes', report_name='dynamic_element'))

Lo hice antes de ver el vídeo y así quedó mi código:

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

class DinamicsElemets(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path = r'C:\chrome-driver\chromedriver.exe')
        driver = self.driver
        driver.get('https://the-internet.herokuapp.com/')
        driver.find_element(By.LINK_TEXT, 'Disappearing Elements').click()

    def test_name_elements(self):
        count = 1
        driver = self.driver
        for i in range(1000):
            try:
                driver.find_element(By.LINK_TEXT, 'Gallery').click()
                time.sleep(2)
                break
            except:
                driver.refresh()
                count += 1
                time.sleep(2)
        
        print(count)


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


if __name__ == '__main__':
    unittest.main(verbosity=2)
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By

class DynamicElements(unittest.TestCase):
    def setUp(self) -> None:
        self.driver = webdriver.Firefox(executable_path = r'.\geckodriver.exe')
        self.driver.get('URL')
        self.driver.maximize_window()

    def test_name_elements(self):
        driver = self.driver

        TRIES_LIMIT = 100
        BUTTON_TEXT = 'gallery'
        tries = 1

        while (tries<TRIES_LIMIT):
            # se captura la cantidad de elementos li (botones)
            elements = driver.find_elements(By.XPATH, '//div[@class="example"]/ul/li')

            if elements[-1].text.lower() == BUTTON_TEXT:
                break

            tries += 1
            driver.refresh()

        print(f'Finished in {tries} tries')
        

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

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

Solucion a elementos dinamicos

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

class DynamicElements(unittest.TestCase):
    def setUp(self) -> None:
        self.driver = webdriver.Chrome(executable_path='./chromedriver')
        self.driver.get('https://the-internet.herokuapp.com/disappearing_elements')
        self.driver.maximize_window()

    def test_name_elements(self):
        driver = self.driver

        count = 1
        while True:
            # se captura la cantidad de elementos li (botones)
            elements = driver.find_elements(By.XPATH, '//div[@class="example"]/ul/li')

            # condicional que valida el ultimo elemento li corresponde a "Gallery"
            if elements[-1].text.lower() == 'gallery':
                # True muestra mensaje con la cantidad de veces que necesito para aparecer boton Gallery y corta script
                print(f'Se necesito refrescar el navegador {count} para que apareciera el boton dinamico')
                break
            else:
                # De lo contrario suma al contador otra vuelta y refresca el navegador
                count += 1
                driver.refresh()

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

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

Aporte

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

class DisappearElement(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.get('https://the-internet.herokuapp.com/')
        driver.maximize_window()
        driver.find_element(By.LINK_TEXT, 'Disappearing Elements').click()

    def test_disappear_element(self):
        driver = self.driver
        
        options = [] # lista vacia
        menu = 5 # cuantas opciones tiene el menu de la
        tries = 1 # Cuantos intentos le lleva a selenium, siempre comienza en 1
        
        # Ciclo While para medir cual es la longitud de opciones
        while len(options) < 5: # mientras options sea menor de 5  se ejecutara el siguiente codigo
            options.clear() # Limpiar lista Options

            for i in range(menu): # para iterar dentro de las opciones
                try:
                    
                    #tenemos que iterar por cada uno de los elementos pero natural tiene el numero del div dode se encuentra
                    # y el elemento de la lista no podemos hacer referencia siempre al numero uno [1]
                    # por lo que debemos cambiarlo por la viariable iterable [{i +1}] es + 1 por que i comoneza en cero
                    # se pone f para que reconozca i 
                    option_name = driver.find_element_by_xpath(f'//*[@id="content"]/div/ul/li[{i +1}]/a')
                    options.append(option_name.text) # agregar en la lista de opciones el valor que se valla mostrando
                    print (options)
                except:
                    print (f"option number {i + 1} is not found")
                    tries += 1 # sumamos 1 a los intentos
                    driver.refresh()
            print((f"Finished in  {tries}")) # imprimimos cuantos intentos llevo 

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

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

Para que la variable tries aumente se debe utilizar el siguiento codigo (Adjunto todo el except statement)

                except:
                    print(f"Option number {i+1} is not found")
                    tries += 1
                    driver.refresh()
def test_name_elements(self):
        driver= self.driver
        contador=0

        while(self.is_element_present(By.XPATH, '//*[@id="content"]/div/ul/li[5]/a')):
            driver.refresh()
            contador+=1
            
        print("La cantidad de veces que se refresco el navegador: ", contador)
    
    def	is_element_present(self, how, what):
        try:  #busca los elementos según el parámetro
            self.driver.find_element(by = how, value = what)
            return False
        except NoSuchElementException as variable:
            return True

Quise intentar algo diferente y así quedó.

    def test_name_element(self):
        driver = self.driver
        element_found = 0
        element_status = False
        counter = 0

        while element_found == 0:
            try:
                gallery_element = driver.find_element_by_xpath('//*[@id="content"]/div/ul/li[5]/a')
                element_status = True
            except:
                element_status = False

            if element_status:
                element_found = 1
                counter += 1
            else:
                element_found = 0
                driver.refresh()
                counter += 1

        sleep(10)
        print(f'Element founded in round {counter}')

Les comparto una forma bastante más simple:

	def test_name_elements(self):
		driver = self.driver 
		tries = 1
		xpath = '//ul/li' # Obtiene la cantidad de elementos de la lista (los botones)

		botones = driver.find_elements(By.XPATH, xpath)

		while len(botones) < 5:
			tries += 1
			driver.refresh()
			botones = driver.find_elements(By.XPATH, xpath)

		print(f'\n.: El elemento gallery apareció luego {tries} intentos! :.')
		time.sleep(3)
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

class DisappearElement(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, 'Disappearing Elements').click()

    def test_disappear_element(self):
        driver = self.driver
        attempt = 1

        hide_button = self.get_element()
        while not hide_button:
            sleep(1)
            attempt += 1
            driver.refresh()
            hide_button = self.get_element()
        
        if not hide_button:
            print(f'El objeto no se encontró')
        else:
            print(f'El objeto se encontró en la recarga {attempt}')
        
        print(hide_button)
        
        sleep(3)

    def get_element(self):
        driver = self.driver
        try:
            return driver.find_element(By.LINK_TEXT, 'Gallery')
        except:
            return False


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

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


Les comparto mi versión del ejercicio:
(Estoy usando selenium 4.1 con python 3.10.1)

def test_found_gallery(self):
        driver = self.driver
        i = 1
        founded = False
        while(not founded):
            try:
                driver.find_element(By.CSS_SELECTOR, '#content > div > ul > li:nth-child(5) > a')
                founded = True
            except:
                driver.refresh()
                i = i + 1
        
        print(f'The aplication takes {i} times to see gallery')

Cosigo solo para saber si Gallery esta presente

        try:
            driver.find_element_by_xpath('//*[@id="content"]/div/ul/li[5]/a')
            print("Gallery is present")
        except:
            print("Gallery is NOT present")
import unittest
from selenium import webdriver


class DynamicElements(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('Disappearing Elements').click()

    def test_name_elements(self):
        driver = self.driver

        options = []
        menu = 5
        tries = 1

        while len(options) < 5:
            options.clear()

            for i in range(menu):
                try:
                    option_name = driver.find_element_by_xpath(
                        f"/html/body/div[2]/div/div/ul/li[{i + 1}]/a")
                    options.append(option_name.text)
                    print(options)
                except:
                    print(f'Option number {i + 1} is NOT FOUND')
                    tries += 1
                    driver.refresh()

        print(f'Finished in {tries} tries')

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


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

Adjunto mi solución, en este caso los sleep solo estan para poder visualmente controlar las recargas.

import unittest
from selenium import webdriver
from time import sleep


class Reto2(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/disappearing_elements")

    def test2(self):
        sleep(2)
        count_menu = []
        recargas = 0
        while len(count_menu) != 5:
            count_menu = self.driver.find_elements_by_tag_name("li")
            if len(count_menu) == 5:
                break
            recargas += 1
            self.driver.refresh()
            sleep(2)
        print(f'Nos tomo {recargas} recargas')

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


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

Reto

Les comparto mi versión del reto

import unittest

from selenium import webdriver
from selenium.webdriver.common.by import By

from common import SERVICE
from common import CHROME_OPTIONS

class DynamicElementsTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        cls.driver = webdriver.Chrome(
            service=SERVICE,
            options=CHROME_OPTIONS,
        )
        cls.driver.get('https://the-internet.herokuapp.com/disappearing_elements')
        cls.driver.maximize_window()
        cls.driver.implicitly_wait(1)

    def test_name_elements(self):
        tries = 0
        expected_menu_items = 5
        menu_items_found = 0

        while menu_items_found < expected_menu_items:
            if tries > 1:
                self.driver.refresh()
                self.driver.implicitly_wait(1)

            items = self.driver.find_elements(By.XPATH, '//*[@id="content"]/div/ul/li')
            print([item.text for item in items])

            menu_items_found = len(items)
            tries += 1

        print(f'Finished in {tries} tries.')

    @classmethod
    def tearDownClass(cls) -> None:
        cls.driver.quit()


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

De los mejores cursos que he tomado, me gusta mucho como se explica el profe y la capacidad de hacerme entender todo. Excelente!

aqui esta mi codigo

        driver = self.driver
        tries = 1
        
    while True:
            
        elements = driver.find_elements_by_xpath('//div[@class="example"]/ul/li')
            
        if len(elements) == 5 :
            print('el numero de intentos fue ', tries)
            break
        else:
            tries += 1
            driver.refresh()

code

import unittest
from pyunitreport import HTMLTestRunner
from selenium import webdriver
from time import sleep

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('Disappearing Elements').click()


    def test_name_elements(self):
        driver = self.driver

        options = []
        menu = 5
        tries = 1

        while len(options)<5:
            options.clear()

            for i in range(menu):
                try:
                    option_name = driver.find_element_by_xpath(f'/html/body/div[2]/div/div/ul/li[{i+1}]/a')
                    options.append(option_name.text)
                except:
                    print(f'Option number {i +1} is Not Found')
                    tries + 1
                    driver.refresh()
        print(f'finish in {tries}')

                    

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

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

Yo lo hice así 🤠

import unittest
from selenium import webdriver
from time import sleep

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('Disappearing Elements').click()
        return super().setUp()
    
    def test_dynamic_elements(self):
        driver = self.driver
        
        self.assertTrue('disappearing_elements'in driver.current_url)
        intentos = 0
        while True:
            intentos += 1
            gallery = driver.find_element_by_class_name('example')
            elements = gallery.find_elements_by_tag_name('a')
            if len(elements) == 4:
                driver.refresh()
            else:
                break
        print(f"Numero de intentos = {intentos}")

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

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

Ahora comparto la versión mejorada después de ver la clase, se ve mucho más elegante.

Esto me recuerda a un profesor en la universidad que nos mencionó:

Pueden pensar en la solución a este problema y seguramente la encontrarán. Pero lo más probable es que la primera solución que encuentren no va a ser la más eficiente.

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

class RefreshUntil(unittest.TestCase):

    @classmethod
    def setUp(cls):
        options = Options()
        options.binary_location = '/snap/brave/119/opt/brave.com/brave/brave'
        cls.driver = webdriver.Chrome(options = options, executable_path="./chromedriver")
        driver = cls.driver
        driver.get("https://the-internet.herokuapp.com/disappearing_elements")
        driver.maximize_window()
    
    def test_refresh_until(self):
        driver = self.driver

        attempts = 0

        menu_options = driver.find_elements_by_tag_name("li")

        while len(menu_options)<5:
            
            driver.refresh()
            attempts += 1


        print(f"Took {attempts} attempts to get the link")
        print(f"The dissappearing link text was {menu_options[-1].text}")

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

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

Esta es mi versión, la hice antes de ver la del profesor. Creo lo que no es cool de la mia es que repito el bloque try except dos veces y que en teoria ya se sabe cuál es el link que debe aparecer.

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

class RefreshUntil(unittest.TestCase):

    @classmethod
    def setUp(cls):
        options = Options()
        options.binary_location = '/snap/brave/119/opt/brave.com/brave/brave'
        cls.driver = webdriver.Chrome(options = options, executable_path="./chromedriver")
        driver = cls.driver
        driver.get("https://the-internet.herokuapp.com/disappearing_elements")
        driver.maximize_window()
    
    def test_refresh_until(self):
        driver = self.driver

        attempts = 0

        try:
            driver.find_element_by_link_text("Gallery")
            present = True
        except:
            present = False


        while not present:
            driver.refresh()
            attempts += 1

            try:
                driver.find_element_by_link_text("Gallery")
                present = True
            except:
                present = False

        print(f"Took {attempts} attempts to get the link")

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

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

Profe, el texto del except, creo que debería decir: “The option number {i} was not found” ya que está en pasado.

Controles dinámicos, son aquello que tienen condiciones para aparecer en ocaciones y en otras no.

Esta es mi solución^^, aunque me gusto más el enfoque del profesor

import unittest
from time import sleep
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
from selenium.common.exceptions import WebDriverException

class DynamicElements(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path='./chromedriver')
        driver = self.driver
        driver.implicitly_wait(10)
        driver.maximize_window()
        driver.get('/ disappearing_elements')

    def test_name_elements(self):
        tries = 1
        while True: 
            try:
                result = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//a[@href="/gallery/"]')))
                if result:
                    break
            except WebDriverException:
                tries += 1
                self.driver.refresh()
        print('\n\n', 'Finished in', tries, 'tries')
        

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


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


Excelente practica aqui les dejo el codigo de la clase explicado con comentarios:

import unittest
from selenium import webdriver
from time import sleep

class DynamicElements(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox(executable_path= r'./geckodriver.exe')
        driver = self.driver
        driver.implicitly_wait(10)
        driver.maximize_window()
        driver.get('https://the-internet.herokuapp.com/')
        driver.find_element_by_link_text('Disappearing Elements').click()

    def test_name_elements(self):
        driver = self.driver

        #Lista vacia para almacenar los elementos del menu
        options = []

        #Elementos existentes
        menu = 5

        #Intentos de refrescamiento iniciara en 1 por que al ingresar se contara como un intento
        tries = 1

        #Bucle while para iniciar proceso
        while len(options) < 5:
            options.clear()

            for i in range(menu):
                #Uso de try y except para evitar errores
                try:
                    #Agregamos la iteracion al xpath para recorrer todos los elementos
                    option_name = driver.find_element_by_xpath(f'/html/body/div[2]/div/div/ul/li[{i +1}]/a')
                    #Agregar elementos a la lista
                    options.append(option_name)
                    print(options)
                except:
                    #Aplicando el iterador para contar los pasos
                    print(f'Option {i+1} has not be found')
                    tries += 1
                    driver.refresh()

        print(f'These was the tries {tries}')
    def tearDown(self):
        driver = self.driver
        driver.close()

if __name__ == '__main__':
    unittest.main()```

Mi aporte:

	def test_browser_navigation(self):
		driver = self.driver

		elements = 5
		tries = 1
		print('\n')
		list_of_elements = []

		while len(list_of_elements) < 5:
			list_of_elements.clear()
			for i in range(elements):
				try:
					element = driver.find_element_by_xpath('//*[@id="content"]/div/ul/li[{}]/a'.format(i+1))
					list_of_elements.append(element.text)
				except:
					tries +=1
					driver.refresh()

			print(list_of_elements)

		print('Number of tries: {}'.format(tries))

Excelente ejercicio al tratar de buscar elementos estáticos de manera automática con el uso de ciclos y try-except!!!

Consejo para alumnos del futuro: En el find element asegúrense de cambiar el find_element_by_link_text() por el texto correcto.

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
from time import sleep
from selenium.webdriver.common.by import By #Hacer referencia a un elemento del sitio web, para interactuar
from selenium.webdriver.support.ui import WebDriverWait # Modulo para  manejo de esperas explicitas
from selenium.webdriver.support import expected_conditions as EC #esperas explicitas




class AddRemoveElements(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(''*****************) #colocar el link
        driver.find_element_by_link_text('Disappearing Elements').click()
        

    def test_name_elemnts(self):
        
        driver = self.driver
        options = []
        menu = 5
        tries = 1
        while len(options) < 5:
            options.clear()     
            for i in range(menu):
                try:
                    option_name =  driver.find_element_by_xpath(f'/html/body/div[2]/div/div/ul/li[{i+1}]/a')
                    options.append(option_name.text)
                    print(options)
                except:
                    print(f'Option number {i + 1} is NOT FOUND')
                    tries += 1
                    driver.refresh()

        print(f'Finished in {tries}')
            


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


   
if __name__ == '__main__':
    unittest.main(verbosity=2)```
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest
import time


class DynamicElements(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox(executable_path='../geckodriver.exe')
        driver = self.driver
        driver.get('URL DEL RETO')
        driver.maximize_window()
        driver.implicitly_wait(30)

    def test_name_elements(self):
        driver = self.driver
        tries = 0
        menu = 0
        while menu < 5:
            tag_li = driver.find_elements_by_tag_name('li')
            menu = len(tag_li)
            tries += 1
            driver.refresh()
        print(f'Number of tries: {tries}')

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


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

Este es el enfoque del ejercicio.

import unittest
import selenium
from selenium import webdriver

class DynamicElements(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path = '../chromedriver_win32/chromedriver.exe') # le asignamos el driver con la ruta, en caso de ser mac no le indicamos la extension
        driver = self.driver
        driver.get('Aqui la pagina web') # platzi bloque sitios http
        driver.maximize_window()
        driver.implicitly_wait(15)
        driver.find_element_by_link_text('Disappearing Elements').click()

    def test_name_element(self):
        driver = self.driver
        tries = 1
        while True:
            try:
                self.driver.find_element_by_link_text('Gallery')
                break
            except:
                tries +=1
                self.driver.refresh()


        print(f'Se encontró el elemento y se realizó {tries} intentos')
    
    def tearDown(self):
        self.driver.quit()


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