Check if any alert exists using selenium with python.

SeleniumAutomation TestingTesting Tools

We can check if any alert exists with Selenium webdriver. An alert is designed on a webpage to notify users or to perform some actions on the alert. It is designed with the help of Javascript.

An alert can be of three types – prompt, confirmation dialogue box or alert. Selenium has multiple APIs to handle alerts with an Alert interface. To check the presence of an alert we shall use the concept of explicit wait in synchronization.

As we know, explicit wait is developed based on Expected condition for a specific element. For the alerts, we shall verify if alert_is_present exists after a specific wait time. If present, we shall accept it. Entire verification shall be inside a try except block.

Let us see if the above alert is present in the page. WebDriverWait class along with ExpectedCondition is used for an explicit wait condition.


Code Implementation.

from selenium import webdriver
from import WebDriverWait
from import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
# maximize with maximize_window()
# identify element and click()
// alert_is_present() expected condition wait for 5 seconds
   WebDriverWait(driver, 5).until (EC.alert_is_present())
   // switch_to.alert for switching to alert and accept
   alert = driver.switch_to.alert
   print("alert Exists in page")
except TimeoutException:
   print("alert does not Exist in page")


Updated on 28-Aug-2020 13:13:17