How to handle alert prompts in Selenium Python ?

Selenium’s Python Module is built to perform automated testing with Python. Alerts are a way to show popups in the browser for either accepting data or displaying data. Selenium provides methods to handle alerts of all kinds. class selenium.webdriver.common.alert.Alert(driver) handles all alerts in Selenium Python. It contains methods for dismissing, accepting, inputting, and getting text from alert prompts. The two major tasks in alerts are accepting an alert or dismissing a alert.
Selenium provides two methods for the same –

Alert(driver).accept()
Alert(driver).dismiss()

Alert Methods

The major methods during handling of alerts in Selenium include –

  • accept() – Accepts the alert available.
  • dismiss() – Dismisses the alert available.
  • send_keys(keysToSend) – Send Keys to the Alert.
  • text – Gets the text of the Alert.

How to operate on an alert prompt using Selenium Python ?

To illustrate alerts, let’s write manual javascript alert and check various methods on the same. We have created an example link – https://ide.geeksforgeeks.org/tryit.php/WXYeMD9tD4

Program –

filter_none

edit
close

play_arrow

link
brightness_4
code

# import webdriver
from selenium import webdriver
  
# import Alert 
from selenium.webdriver.common.alert import Alert
  
# create webdriver object
driver = webdriver.Firefox()
  
# get ide.geeksforgeeks.org
driver.get("https://ide.geeksforgeeks.org / tryit.php / WXYeMD9tD4")
  
# create alert object
alert = Alert(driver)
  
# get alert text
print(alert.text)
  
# accept the alert
alert.accept()

chevron_right


Output –
alerts-in-python-selenim



Terminal Output –
terminal-output-alerts-in-selenium-python

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up

Software Developer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.