How to click on a pop up dialog in Selenium?

To handle browser dialog pop-ups in Selenium like this one seen on cart page:

cart clear alert as seen on

We can explicitly wait for alert_is_present() expected condition. For example, let's take a look at a real alert pop up on the cart page of

from selenium import webdriver
from import By
from import WebDriverWait
from import expected_conditions as EC
from selenium.common.exceptions import NoAlertPresentException

driver = webdriver.Chrome()

# navigate to the product page and add a product to the cart
add_to_cart_button = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".add-to-cart"))

# navigate to the cart and attempt to clear it
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"))

    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()  # press "Yes"
        alert.dismiss()  # press "No"
except NoAlertPresentException:
    print("No alert is present")

# print out the remaining items in the cart
cart_items = driver.find_elements(By.CSS_SELECTOR, ".cart-item .cart-title")
print(f"items in cart: {len(cart_items)}")  # should be 0 if the cart was cleared

In the example above, we navigate to the product page and add a product to the cart. Then we navigate to the cart and attempt to clear it. If the alert is present, we check whether the alert message contains the text "clear your cart" and if so, we click "Yes" to clear the cart. Otherwise, we click "No" to cancel the dialog.

Question tagged: Selenium

Related Posts

How to Use Chrome Extensions with Playwright, Puppeteer and Selenium

In this article, we'll explore different useful Chrome extensions for web scraping. We'll also explain how to install Chrome extensions with various headless browser libraries, such as Selenium, Playwright and Puppeteer.

Intro to Web Scraping using Selenium Grid

In this guide, you will learn about installing and configuring Selenium Grid with Docker and how to use it for web scraping at scale.

How to Scrape Google Maps

We'll take a look at to find businesses through Google Maps search system and how to scrape their details using either Selenium, Playwright or ScrapFly's javascript rendering feature - all of that in Python.