selenium
  1. selenium-handling-alerts

Handling Alerts - Selenium WebDriver

Alerts are common pop-up windows in web applications that prompt users for input or to confirm an action. Selenium WebDriver provides the ability to handle these alerts programmatically.

Syntax

The syntax for handling alerts with Selenium WebDriver is as follows:

alert = driver.switch_to.alert
alert.accept()
alert.dismiss()

Example

from selenium import webdriver

# create a new instance of Firefox driver
driver = webdriver.Firefox()

# navigate to website with alert
driver.get("https://www.example.com")

# click on button that triggers alert
driver.find_element_by_id("alert-btn").click()

# switch to alert and accept it
alert = driver.switch_to.alert
alert.accept()

# close the browser
driver.quit()

Explanation

In the above example, we use the Firefox driver to navigate to a website where we have a button that triggers an alert when clicked. We find the button by its ID and simulate a click using the click method.

Next, we use the switch_to.alert method to switch the focus of the driver to the active alert. We then accept the alert by calling the accept method.

Finally, we close the browser using the quit method.

Use

Handling alerts is essential when testing web applications with Selenium WebDriver. Alerts can occur in many scenarios, such as when deleting a record or closing a form with unsaved changes. Selenium provides the ability to simulate user input for these alerts through the use of the switch_to.alert method.

Important Points

  • Use switch_to.alert method to switch focus to the active alert.
  • Use accept method to accept the alert.
  • Use dismiss method to dismiss the alert.

Summary

Selenium WebDriver provides the ability to handle alerts through the use of the switch_to.alert method, allowing for the simulation of user input for confirmations or prompts in web applications.

Published on: