Confirmation alert handling in Selenium Python - Build an Automation Script
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 TimeoutException from selenium.webdriver.common.alert import Alert import unittest class TestConfirmationAlertHandling(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://example.com/items') # Replace with actual URL self.wait = WebDriverWait(self.driver, 10) def test_delete_item_confirmation_alert(self): driver = self.driver wait = self.wait # Locate the delete button for the first item delete_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.item .delete-btn'))) delete_button.click() try: # Wait for alert to be present alert = wait.until(EC.alert_is_present()) # Verify alert text alert_text = alert.text self.assertEqual(alert_text, 'Are you sure you want to delete this item?') # Accept the alert alert.accept() # Verify the item is removed from the list # Wait until the first item is no longer present or list updates wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '.item'))) # Optionally, check the count of items decreased items = driver.find_elements(By.CSS_SELECTOR, '.item') self.assertTrue(len(items) < 1, 'Item was not deleted') except TimeoutException: self.fail('Confirmation alert did not appear') def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
This test script uses Selenium with Python's unittest framework to automate the confirmation alert handling.
setUp: Opens the browser and navigates to the items page.
test_delete_item_confirmation_alert: Clicks the delete button on the first item, waits explicitly for the alert, verifies the alert text, accepts the alert, then waits for the item to be removed from the list and asserts the deletion.
Explicit waits ensure the test waits only as long as needed for elements or alerts, avoiding fixed delays.
tearDown: Closes the browser after the test.
This approach follows best practices by using explicit waits, proper locators, and handling exceptions to make the test reliable and maintainable.
Now add data-driven testing with 3 different items to delete, verifying alert handling for each.