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.

Example

Code Implementation.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
# identify element and click()
l=driver.find_element_by_name("submit")
l.click()
// alert_is_present() expected condition wait for 5 seconds
try:
   WebDriverWait(driver, 5).until (EC.alert_is_present())
   // switch_to.alert for switching to alert and accept
   alert = driver.switch_to.alert
   alert.accept()
   print("alert Exists in page")
except TimeoutException:
   print("alert does not Exist in page")
driver.close()

Output

raja
Published on 28-Aug-2020 16:41:41
Advertisements