Skip to main content

Add Remove Eelements

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


class AddRemoveElementsTest:
def __init__(self, driver_path):
"""Initialize the WebDriver."""
service = Service(driver_path)
self.driver = webdriver.Chrome(service=service)

def navigate_to_url(self, url):
"""Navigate to the specified URL."""
self.driver.get(url)

def add_elements(self, number_of_elements):
"""Clicks the 'Add Element' button the specified number of times."""
add_button = self.driver.find_element(
By.XPATH, "//button[text()='Add Element']")
for _ in range(number_of_elements):
add_button.click()

def remove_elements(self, number_of_elements):
"""Clicks the 'Delete' button for all the elements added."""
# Assuming that clicking the 'Add Element' button adds elements with a 'Delete' button
delete_buttons = self.driver.find_elements(
By.CLASS_NAME, 'added-manually')
for i in range(number_of_elements):
if delete_buttons:
delete_buttons[i].click()

def close_browser(self):
"""Close the browser."""
self.driver.quit()


if __name__ == "__main__":
# Replace with the actual path to your WebDriver
DRIVER_PATH = 'D:/testtools/chromedriver.exe'
TEST_URL = 'https://practice.expandtesting.com/add-remove-elements'

# Initialize the test
test = AddRemoveElementsTest(DRIVER_PATH)

# Navigate to the test URL
test.navigate_to_url(TEST_URL)

# Add elements
number_of_elements_to_add = 3

test.add_elements(number_of_elements_to_add)

# Optional: Wait a bit to see the elements
time.sleep(20)

# Remove elements
test.remove_elements(number_of_elements_to_add)

# Close the browser
test.close_browser()