Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Agregar y eliminar elementos

16/24
Recursos

Aportes 37

Preguntas 6

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Usé en la línea 29:

delete_button = driver.find_element_by_class_name('added-manually')

Ya que todos los elementos a eliminar comparten la misma clase

Aqui mi aporte, si alguien quiere ver apuntes de las clases , comparto mi repositorio https://github.com/jeyfredc/Curso-de-introduccion-a-Selenium-con-Python

import unittest
from selenium import webdriver
from time import sleep

class AddRemoveElements_Reto(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('Add/Remove Elements').click()

    
    def test_add_remove(self):
        driver = self.driver

        elements_added = int(input('Cuantos elementos desea agregar?: '))

        add_button = driver.find_element_by_xpath('//*[@id="content"]/div/button')

        sleep(3)

        for i in range(elements_added):
            add_button.click()

        elements_removed = int(input('cuantos elementos desea remover?: '))

        while elements_removed > elements_added:
        
            for i in range(elements_removed):

                    print("Intentas remover mas elementos de los que ingresaste")

                    if elements_removed > elements_added:

                        elements_removed = int(input('cuantos elementos desea remover?: '))
                        
                        delete_button = driver.find_element_by_xpath('//*[@id="elements"]/button[1]')
                        delete_button.click()
                        break   

        sleep(3)                    
        total_elements = elements_added - elements_removed

        if total_elements == 1:

            print(f'Removiste {elements_removed} elementos, queda {total_elements} elemento')

        elif total_elements > 1 or total_elements < 1:
            
            print(f'Removiste {elements_removed}, quedan {total_elements} elementos')  


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


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

Estan sabrosones los retos 👨‍💻

Revisando un poco como funciona la pagina me di cuenta de que ejecuta una función llamada addElement() cada vez que hacemos click en el botón por lo que no es necesario referenciarlo. Se podría hacer algo como esto self.drive.execute_script("addElement()") y para eliminar sería algo asi: self.drive.execute_script("deleteElement()"). Con esta implementación no necesitaríamos el try except.

Realicé el reto sin la sentencia try para agilizar la prueba ya que me tardaba mucho en mi compu. Saludos.

import unittest 
from selenium import webdriver
from time import sleep 

class AddRemoveElements(unittest.TestCase):

	def setUp(self): #ejecutar todo lo necesario antes de hacer la prueba
		self.driver = webdriver.Chrome(executable_path = r'../chromedriver')
		driver = self.driver
		driver.implicitly_wait(10)
		driver.maximize_window()
		driver.get('http://the-internet.herokuapp.com/')
		driver.find_element_by_xpath('/html/body/div[2]/div/ul/li[2]/a').click()


	def test_browser_navigation(self):
		driver = self.driver
		elements_added = int(input('How many elements will you add? '))
		elements_removed = int(input('How many elements will you remove? '))
		total_elements_in_screen = elements_added - elements_removed

		add_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/button')

		if total_elements_in_screen > 0:

			for i in range(elements_added):
				add_button.click()
			

			for i in range(elements_removed):
				delete_button = driver.find_element_by_class_name('added-manually')
				delete_button.click()

			print('There are {} elements to show'.format(total_elements_in_screen))
		
		elif total_elements_in_screen == 0:
			print('There are not elements to show')

		else:
			print('you are trying to delete more items than you could add')


	def tearDown(self): #acciones para finalizar
		sleep(1)
		self.driver.implicitly_wait(3)
		self.driver.close()

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

Algo que he notado, ahora que empezé a trabajar en el mundo Tech, es que no es buena idea usar el x-path para el caso de las automatizaciones, sino el ID. Aunque depende, si tienes la posibilidad de solicitar que coloquen el id a las etiquetas, debes hacerlo, así no tendras problemas cuando el código fuente cambie.

Aporte con esperas implicitas:

def test_browser_navigation(self):
		driver = self.driver
		elements_added = int(input('How many elements will you add? '))
		elements_removed = int(input('How many elements will you remove? '))
		total_elements = elements_added - elements_removed

		add_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/button')

		for i in range(elements_added):
			add_button.click()


		for i in range(elements_removed):

			try:
				delete_button = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.CLASS_NAME, 'added-manually')))
				delete_button.click()
			except:
				print('you are trying to delete more buttons than you added')
				break

		if total_elements < 0:
			print('you are trying to delete more elements than you have')
		else:
			print('you have the total of {} elements on screen'.format(total_elements))

Realice el reto haciendo que el usuario no pueda equivocarse en las cantidades, si fallara, seria por alguna otra causa, sin embargo esta controlado con el try/except

def test_add_remove(self):
    add = int(input('< Cuantos elementos deseas agregar? '))
    remove = int(input('< Cuantos elementos deseas remover? '))
    total = add - remove

    try:
      while total < 0:
        print('> Intentas borrar mas elementos de los que crearas, intenta de nuevo')
        add = int(input('< Cuantos elementos deseas agregar? '))
        remove = int(input('< Cuantos elementos deseas remover? '))
        total = add - remove

      add_button = self.driver.find_element_by_xpath('//*[@id="content"]/div/button')

      for _ in range (add):
        add_button.click()
        sleep(0.5)

      element_list = self.driver.find_elements_by_class_name('added-manually')
      for _ in range(remove):
        element = element_list.pop(0)
        element.click()
        sleep(0.5)
    except:
      print('> Ha ocurrido un error...')

Yo cree un script que hacia uso de random para los add/remove

from time import sleep
import unittest
import random
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By


class CreateUser(unittest.TestCase):

    def setUp(self):
        chrome = Service(r"C:\Drivers\chrome\chromedriver.exe")
        self.driver = webdriver.Chrome(service=chrome)
        self.driver.implicitly_wait(1)
        self.driver.maximize_window()
        self.driver.get("the-internet.herokuapp.com/")

    def test_a_add_remove(self):
        add_remove = self.driver.find_element(
            By.XPATH, '/html/body/div[2]/div/ul/li[2]/a')
        add_remove.click()
        try:
            a = random.randrange(100)
            b = random.randrange(100)

            while a >= 0:
                add_button = self.driver.find_element(
                    By.XPATH, "/html/body/div[2]/div/div/button")
                add_button.click()
                a = a - 1

            while b >= 0:
                delete_button = self.driver.find_element(
                    By.XPATH, "/html/body/div[2]/div/div/div/button")
                delete_button.click()
                b = b - 1

        except Exception as erre:
            print(f"*-*-*-*-*-*-*-*-*-* \n*-*-*-*-*-*-*-*-*-* \n {erre}")

        self.driver.back()
        sleep(1)

    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
from time import sleep

class AddRemoveElements(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.find_element(By.LINK_TEXT, 'Add/Remove Elements').click()

    def test_add_button_delete(self):
        add_element_number = int(input('How many elements will you add?: '))
        delete_element_number = int(input('How many elements will you remove?: '))
        sleep(5)

        total_elements = add_element_number - delete_element_number

        driver = self.driver
        button_add_element = driver.find_element(By.XPATH, '//*[contains(text(), "Add Element")]')
        [button_add_element.click() for _ in range(add_element_number)]

        sleep(5)

        get_buttons_delete = driver.find_elements(By.CLASS_NAME, 'added-manually')
        for i in range(delete_element_number):
            try:
                get_buttons_delete[i].click()
            except:
                print('You want to delete more elements than you see on window.')
        
        if add_element_number <= delete_element_number:
            print('All buttons was deleted.')
        else:
            print(f'There are {add_element_number - delete_element_number} delete buttons on window.')

        sleep(5)

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

if __name__ == '__main__':
    unittest.main(verbosity=1)
import unittest
from selenium import webdriver
from time import sleep

class TestingMercadoLibre(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path = './chromedriver')
        driver = self.driver
        driver.get('https://www.mercadolibre.com')
        driver.maximize_window()

Reto

import unittest

from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.by import By

from common import SERVICE
from common import CHROME_OPTIONS

class CompareProductsTestCase(unittest.TestCase):

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

    def test_add_remove(self):

        elements_to_add = int(input('How many elements would you like to add?'))
        elements_to_delete = int(input('How many elements would you like to delete?'))

        add_button: WebElement
        add_button = self.driver.find_element(By.XPATH, '//*[@id="content"]/div/button')
        
        for i in range(elements_to_add + 1):
            add_button.click()
            self.driver.implicitly_wait(1)

        self.driver.implicitly_wait(10)
        elements = self.driver.find_elements(By.CLASS_NAME, 'added-manually')
        
        try:
            for idx in range(elements_to_delete + 1):
                elements[idx].click()
                self.driver.implicitly_wait(1)
        except IndexError:
            pass

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


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

Comparto mi manera de tratar la excepción para cuando un usuario ingrese más elementos a eliminar que por agregar.
Debe ir antes del for para borrar los botones. La variable remove es elements_remove y add es elements_added

<        if remove > add:
            remove = add> 

codigo de la leccion

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('Add/Remove Elements').click()

    def test_add_remove(self):
        driver = self.driver

        elements_added = int(input('how many elements will you add: '))
        elements_remove = int(input('How many elements will you remove: '))
        total_elements = elements_added - elements_remove

        add_button = driver.find_element_by_xpath('//*[@id="content"]/div/button')

        sleep(3)

        for i in range(elements_added):
            add_button.click()

        for i in range(elements_remove):
            try:
                delete_button = driver.find_element_by_xpath('//*[@id="elements"]/button[1]')
                delete_button.click()
            except :
                print('your try to delete more elements that exist')
                break
        if total_elements >  0:
            print(f'there are {total_elements} in Screen')

        else:
            print('there are 0 elements on screen ')

        sleep(3)



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

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

Solo hice que jugara un poco la página. Lo hice antes de ver la clase como lo dice "RETO"🤠

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('Add/Remove Elements').click()
        return super().setUp()
    
    def test_Add_Remove_Element(self):
        driver = self.driver
        #comprobando que estamos en la seccion de add_remove
        self.assertTrue('add_remove_elements'in driver.current_url)

        button_add = driver.find_element_by_xpath('//*[@id="content"]/div/button')
        
        for i in range (3):
            for x in range (3):
                button_add.click()
                sleep(1)
            
            button_remove = driver.find_element_by_class_name('added-manually')
            button_remove.click()
            sleep(1)
        
                
    def tearDown(self) -> None:
        self.driver.close()
        return super().tearDown()


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

Comparto el codigo del reto que hice:

import unittest
from selenium import webdriver
from time import sleep

class AddDeleteElements(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('Add/Remove Elements').click()

    def test_add_remove(self):
        driver = self.driver
        total_elements = -1

        while total_elements < 0:
            elements_added = int(input('How many will you add? '))
            elements_removed = int(input('How many elements will you remove? '))
            total_elements = elements_added - elements_removed

            if total_elements < 0:
                print("[ERROR] You're trying to delete more elements that the exitents")
        
        add_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/button')

        for _ in range(elements_added):
            add_button.click()
            sleep(2)
        
        for _ in range(elements_removed):
            delete_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/div/button[1]')
            delete_button.click()
            sleep(2)
                
        print(f'There are {total_elements} elements on screen')

        sleep(3)

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

if _name_ == "_main_":
    unittest.main(verbosity=2)
def test_add_remove(self):
        driver = self.driver
        userAdd = int(input("How many elements will you add?: "))
        userRemove = int(input("How many elements will you remove?: "))
        remainderElements = userAdd - userRemove
        addButton = driver.find_element_by_css_selector("button")
        for i in range(userAdd):
            addButton.click()

        removeElements = driver.find_elements_by_css_selector(".added-manually")
        for i in range(userRemove):
            removeElements[i].click()

        print(f"Total elements on screen : {remainderElements}")

        sleep(4)

Una manera distinta de obtener los elementos, y seleccionar el número de elementos que se desea eliminar.

El sitio que viene en el sitio del ejercicio está bastante bueno porque tiene tips para usar selenium, varios me pareció haberlos visto en alguna pregunta en clases anteriores.

Aquí mi versión. Usé implicitly_wait(1) porque la sintaxis es más sencilla y practicamente el sitio tarda nada en agregar y quitar los botones.

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
from selenium.webdriver.support.select import Select

class AddRemove(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/add_remove_elements/")
        driver.maximize_window()
    
    def test_add_remove(self):
        driver = self.driver
        ea = int(input("How many add?"))
        er = int(input("How many remove?"))
        
        if er > ea:
            er = ea
            
        tot = ea - er

        add_btn = driver.find_element(By.XPATH, '//*[@id="content"]/div/button')
        for i in range(ea):
            add_btn.click()

        driver.implicitly_wait(1)
        rm_btns = driver.find_elements(By.CLASS_NAME, "added-manually")

        for i in range(er):
            rm_btns[i].click()

        try:
            l=len(driver.find_elements(By.CLASS_NAME, "added-manually"))
        except:
            l=0

        self.assertEqual(tot, l)

        #WebDriverWait(driver, 10).until(lambda s: s.find_element_by_id("select-language").get_attribute('length') == 3)

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

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

Dejo mi código, solo puse las variables globales para no tener que ir de consola al navegador

import unittest
from selenium import webdriver
from time import sleep

class AddRemoveElements(unittest.TestCase):
    def setUp(self):
        global elements_to_add
        global elements_to_delete
        elements_to_add = int(input('Cuantos elementos quieres agregar?: '))
        elements_to_delete = int(input('Cuantos elementos quieres eliminar?: '))
        self.driver = webdriver.Chrome(executable_path="/Users/gonza/Documents/Gonza/programacion/chromedriver")
        driver = self.driver
        driver.maximize_window()
        driver.get("[enlace a la página principal]")
        driver.find_element_by_xpath('//*[@id="content"]/ul/li[2]/a').click()

        
    def test_add_remove(self):
        add_element_button = self.driver.find_element_by_xpath('//*[@id="content"]/div/button')
        sleep(3)
        for i in range(elements_to_add):
            add_element_button.click()
        sleep(3)
        
        remove_element_button = self.driver.find_element_by_xpath('//*[@id="elements"]/button[1]')
        for i in range(elements_to_delete):
            try:
                remove_element_button.click()        
            except:
                print('Estás intentando eliminar más elementos de los añadidos')
                break
        sleep(3)

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

def run():
    unittest.main(verbosity=2)

if __name__=="__main__":
    run()```

Lo bueno de trabajar con Selenium, es que podemos trabajar con todas las herrmientas que nos da nuestro lenguaje de preferencia.

Esta fue mi solución usando list comprehensions y en vez de usar try/except usé un if para confirmar que estoy tratando de eliminar una menor de los elementos (sino elimina todos los que hay)

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
from time import sleep


class AddRemoveElements(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path='./chromedriver')
        driver = self.driver
        driver.implicitly_wait(30)
        driver.maximize_window()
        driver.get('LINK')

    def test_browser_navigation(self):
        n = int(input('\n\nEnter a number:  '))
        add_element = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[@onclick="addElement()"]')))
        [ add_element.click() for i in range(n) ]

        n = int(input('\nEnter a number:  '))

        if len(self.driver.find_elements_by_xpath('//button[@onclick="deleteElement()"]')) >= n:
            [ WebDriverWait(self.driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//button[@onclick="deleteElement()"]'))).click() for i in range(n) ]
        else:
            [ WebDriverWait(self.driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//button[@onclick="deleteElement()"]'))).click() for i in range(len(self.driver.find_elements_by_xpath('//button[@onclick="deleteElement()"]'))) ]

        sleep(3)

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


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

No sé si a alguien más le dio un error Selenium porque ni siquiera podía encontrar el botón de agregar, y es que la url debe ser la siguiente: https://the-internet.herokuapp.com/add_remove_elements/

Realicé el reto con pausas explicitas

Así quedó el mio, el excepto lo deje solo con el break para terminar con un if que me indica que mensaje dejar

    def test_agregar_borrar(self):
        driver = self.driver

        elementos_agregados = int(input("Cuantos elementos agregar?: "))
        elementos_eliminados = int(input("Cuantos elementos quieres eliminar?: "))
        elementos_totales = elementos_agregados - elementos_eliminados

        boton_agregar = driver.find_element_by_xpath('//*[@id="content"]/div/button')
        

        sleep(3)

        for i in range(elementos_agregados):
            boton_agregar.click()

        for i in range(elementos_eliminados):
            try:
                boton_eliminar = driver.find_element_by_xpath('//*[@id="elements"]/button[1]')
                boton_eliminar.click()

            except:  
                break

        sleep(5)

        if elementos_totales > 0:
            print("Luego de la prueba quedaron " + str(elementos_totales) + " botones restantes")
        else:
            print("Estas intentando eliminar mas botones de los que agregaste")```
def test_add_remove(self):
    driver = self.driver
    elements_added = 5


    add_button = driver.find_element_by_xpath('//*[@id="content"]/div/button')

    for i in range(0,elements_added):
        add_button.click()
        sleep(1)

    deletes=driver.find_element_by_id('elements')
    butttons=deletes.find_elements_by_class_name('added-manually')

    print(">>>>",deletes,'\n')
    print(">>>>", type(deletes), '\n')
    print(">>>>", type(butttons), '\n')
    elements_removed = len(butttons)
    print(">>>>",elements_removed,' <<<<< PORFA FUNCIONEEEEEEEEEEEEEEEEEEEEEEEEEEEE', '\n')

    for btn in butttons:
        btn.click()
        sleep(1)

a ver en teoria mi codigo esta bien mas sin embargo, no entiendo porque me carga la pagina perfectamente, luego cuando ejecuta el metodo agregar y borrar abre una nueva pagina en la cual evidentemente no consigue ningun test

import unittest
from selenium import webdriver
import time

class AddRemoveElements(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(executable_path=r'C:\dcCrhome\85\chromedriver.exe')
      
    def test_ahose(self):
        driver = self.driver
        driver.implicitly_wait(10)
        driver.get('*******************/')
        driver.find_element_by_link_text('Add/Remove Elements').click()
        driver.maximize_window()

    def test_bdd_and_remove(self):
        driver = self.driver
        elements_added = int(input("How many elements will you add??"))
        elements_removed = int(input("How mane elements will you delete??"))
        total_elements = elements_added - elements_removed
        
        add_buton = driver.find_element_by_xpath('//*[@id="content"]/div/button')
        for _ in range(elements_added):
            add_buton.click()

        
        remove_buton = driver.find_element_by_class_name('added-manually')
        for _ in range(elements_removed):
            try:
                remove_buton
                elements_removed.click()
            except:
                print("You are trying to delet more elements the we have")
                break
        driver.implicitly_wait(30)
        if total_elements > 0:
            
            print(f"there are {total_elements} elements on the screen ")
        else:        
            print(f"Dont have elements on screen ")
        time.sleep(3)

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

if __name__ == "__main__":
    unittest.main(verbosity=2)```
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('*********/') #adicionar URL

    def test_add_remove(self):
        try:
            driver = self.driver
            # elements_added = int(input('How many elements will you add?:  '))
            # elements_remove = int(input('How many elements will you remove?:  '))
            elements_added , elements_remove = menu()
            total_elements = elements_added - elements_remove

            while total_elements < 0:
                print(f'Los elementos borrados: {elements_remove} es mayor a los elementos adiconados: {elements_added}')
                print('')
                elements_added , elements_remove = menu()
                total_elements = elements_added - elements_remove

            add_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/button')

            sleep(3)

            for i in range(elements_added):
                add_button.click()
                sleep(0.2)

            
            for i in range(elements_remove):
                try:
                    delete_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/div/button[1]')
                    delete_button.click()
                    sleep(0.2)
                except:
                    print("You're trying to delete more elemnts the existent..")
                    break

            if total_elements > 0:
                print(f'There are {total_elements} elements on screen')
            else:
                print(f'There are 0 elemnts on screen')

            sleep(3)
        except:
            print('Fatal error....') 
            


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


   
def menu():

    elements_added = int(input('How many elements will you add?:  '))
    elements_remove = int(input('How many elements will you remove?:  '))
    return elements_added, elements_remove


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

mi codigo quedo practicamente similar

def test_add_remove(self):
        driver = self.driver
        add_button = driver.find_element_by_tag_name('button')
        self.assertTrue(add_button.is_enabled())
        elements_added = int(input('How many elments do you want add?: '))
        elements_removed = int(input('How many elments do you want remove?: '))
        
        for _ in range(elements_added):
            add_button.click()
        
        for _ in range(elements_removed):
            try:
                driver.find_element_by_class_name('added-manually').click()
            except:
                print('no hay mas elementos para eliminar')
                break
        sleep(5)

Cree botones aleatorios y luego la cantidad a eliminar depende de la cantidad de botones creados como máximo

Codigo de la clase con comentarios explicados:

import unittest
from selenium import webdriver
from time import sleep

class AddRemoveElements(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('Add/Remove Elements').click()

    def test_add_remove(self):
        driver = self.driver

        #input de cantidad de elementos
        elements_added = int(input('How many elements do you want to add?: '))

        #input cantidad de elementos a eliminar
        elements_remove = int(input('How many elements do you want to remove?: '))

        #total de elementos, para verificar su diferencia
        total_elements = elements_added - elements_remove

        #Buscar el boton de agregar elementos
        add_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/button')
        sleep(3)#Agregar espera 3 segundos

        #Agregar botones
        for i in range(elements_added):
            add_button.click()

        #Eliminar elementos

        for k in range(elements_remove):
            #Utilizar try except para evitar errores
            try:
                delete_button = driver.find_element_by_class_name('added-manually')
                #/html/body/div[2]/div/div/div/button
                delete_button.click()
                sleep(1)

            except:
                print('You are trying to delete more element that you have')
                break

        #Condicional para ver que es lo que esta pasando con los elementos
        if total_elements > 0:
            print(f'There are {total_elements} on screen')
        else:
            print('There are 0 elements on screen')

        sleep(3)#Agregar pausa

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

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

Les comparto el codigo de la clase con las funciones vistas explicadas en comentarios:

import unittest
from selenium import webdriver
from time import sleep

class AddRemoveElements(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('Add/Remove Elements').click()

    def test_add_remove(self):
        driver = self.driver

        #input de cantidad de elementos
        elements_added = int(input('How many elements do you want to add?: '))

        #input cantidad de elementos a eliminar
        elements_remove = int(input('How many elements do you want to remove?: '))

        #total de elementos, para verificar su diferencia
        total_elements = elements_added - elements_remove

        #Buscar el boton de agregar elementos
        add_button = driver.find_element_by_xpath('/html/body/div[2]/div/div/button')
        sleep(3)#Agregar espera 3 segundos

        #Agregar botones
        for i in range(elements_added):
            add_button.click()

        #Eliminar elementos

        for k in range(elements_remove):
            #Utilizar try except para evitar errores
            try:
                delete_button = driver.find_element_by_class_name('added-manually')
                #/html/body/div[2]/div/div/div/button
                delete_button.click()
                sleep(1)

            except:
                print('You are trying to delete more element that you have')
                break

        #Condicional para ver que es lo que esta pasando con los elementos
        if total_elements > 0:
            print(f'There are {total_elements} on screen')
        else:
            print('There are 0 elements on screen')

        sleep(3)#Agregar pausa

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

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

Wow, que interesante un sitio web para poner todo estos conocimientos en practica. aqui se los comparto:

tengo una duda, cuadno descargo un archivo excel por ejemplo y quiero abrirlo de inmediato cual seria el comando para poder ejecutar esta accion.
Se que se puede abrir desde la ruta directa, pero la idea es que cuando termine de descargarse el archivo, este se abra automaticamente
Espero alguien pueda ayudarme

estupendo u.u

así lo hice yo:

import os
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


class AddRemoveElements(unittest.TestCase):

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

    def testAddRemoveElements(self):
        validate_process = self.interface()
        while(validate_process < 0):
            os.system("clear")
            print("T H E  B O X E S  T O  D E L E T E  A R E  M O R E  T H A N  T H E  B O X E S  T O  A D D . T R Y  A G A I N . ")
            validate_process = self.interface()

        WebDriverWait(driver=self.driver , timeout=10).until(method=ec.element_to_be_clickable(locator=(By.XPATH , "/html/body/div[2]/div/div/button")))

        for i in range(self.to_add):
            self.driver.find_element_by_xpath("/html/body/div[2]/div/div/button").click()

        sleep(3)

        for i in range(self.to_delete):
           self.driver.find_element_by_class_name("added-manually").click() 
        sleep(2)
    
    def tearDown(self):
        self.driver.close()

    def interface(self):
        self.to_add = int(input('\nWrite the total boxes to add: '))
        self.to_delete = int(input('\nWrite the total box to delete: '))

        return self.to_add - self.to_delete

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

Muchas gracias Héctor. Me imagino usar esta automatización para probar en videojuegos on line, justamente sacando y colocando objetos al protagonista de mi juego.