Logo New Black

Mastering Selenium: How to Click on Alert Dialog Effectively & Easily

In the realm of automated web testing, dealing with browser dialog pop-ups via Selenium stands as a crucial skill, especially when navigating through scenarios typically encountered on shopping cart pages. A typical challenge involves orchestrating a timely response to alerts that manifest following user actions such as adding items to a shopping cart or attempting its clearance. To seamlessly integrate this functionality into your testing suite, leveraging a robust web scraping API can enhance your ability to simulate and interact with web elements effectively, thereby ensuring your automated tests are as close to real-world user behavior as possible.

An example scenario on a cart page can be illustrated with Selenium by navigating to a product page, adding an item, and then proceeding to the cart to clear it. The process employs the alert_is_present() condition to handle confirmation dialogs effectively:

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 NoAlertPresentException

driver = webdriver.Chrome()

# Navigate to the product page, add an item to the cart
driver.get("https://web-scraping.dev/product/1")
add_to_cart_button = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".add-to-cart"))
)
add_to_cart_button.click()

# Proceed to the cart, initiate cart clearing
driver.get("https://web-scraping.dev/cart")
cart_item = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".cart-full .cart-item"))
)
clear_cart_button = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".cart-full .cart-clear"))
)
clear_cart_button.click()

try:
    alert = WebDriverWait(driver, 10).until(EC.alert_is_present())
    if "clear your cart" in alert.text:
        print(f'Clicking "Yes" to {alert.text}')
        alert.accept()  # Confirm cart clearance
    else:
        alert.dismiss()  # Cancel the action
except NoAlertPresentException:
    print("No alert present")

# Output remaining cart items, expecting 0 after clearance
cart_items = driver.find_elements(By.CSS_SELECTOR, ".cart-item .cart-title")
print(f"Items in cart: {len(cart_items)}")
driver.quit()

This approach delineates the steps to interact with a product page by adding an item to the cart, then moving to the cart page to clear it. Upon encountering a confirmation alert, it verifies the message for specific text before deciding to confirm or cancel the action, demonstrating how Selenium can automate and handle dynamic web elements and user prompts.