Python Selenium handle alerts prompts confirmation popups
In this article, let’s experiment different ways to handle alerts and popups on a web page. Web applications displays alert messages to notify user or prompt popups to get some input from user or confirm popups for confirming an user action; And it is usually a standard practice.
An Alert or Prompt or Confirm popup is a pop-up window and gets triggered by the user performed action or automatically due to some web page settings.
We can broadly categorize the Alerts into following three types.
1. Simple Alert
2. Confirmation Alert
3. Prompt Alert
Purpose of simple alert is to give some information or warning to the user;
Purpose of confirm alert is to take permission from the user before doing something;
Purpose of prompt alert is to take some input from the user.
We will now discuss in detail how to handle the above three types of alerts.
Handle Alert & Popups In Selenium Python
Whenever an Alert gets triggered and a pop-up appears on the web page, the control remains with the parent web page. So first we need to switch or transfer the control to alert pop-up before doing any operations.
This control switching operation can be done by using anyone of below two code snippets.
driver.switch_to.alert
driver.switch_to_alert()
Above two statements returns alert object. We need to have reference to those alert object to perform future operations. We change above code for this to happen.
alert = driver.switch_to.alert
alert = driver.switch_to_alert()
After the control has moved to Alert pop-up, we can do different actions on it using available methods.
Handling A Simple Alert
A Simple Alert pop-up has a message in it along with an ‘Ok’ button. When it is displayed, user clicks on the ‘Ok’ button to accept it or ‘close’ icon to close(dismiss) the popup.
alert.accept() – Will click on OK button
alert.dismiss() – Will click on Cancel button
alert.text – will get the text which is present on the Alert
Handling A Confirmation Alert
A Confirmation Alert pop-up has a message in it along with an ‘Ok’ and ‘Cancel’ button. When it is displayed, user clicks on the ‘Ok’ button to accept it or ‘Cancel’ button to dismiss it. ‘close’ icon also dismisses the pop-up
This alert also has same properties as in Alert – accept(), dismiss(), text
Handling Prompt Alert
A Prompt Alert pop-up has a message in it along with a text box and ‘Ok’ button. When it is displayed, user enters any value in text box and clicks on the ‘Ok’ button to accept. ‘close’ icon dismisses the pop-up.
This pop-up supports one more method send_keys() along with accept(), dismiss() and text.
Note: When you try to send some text using send keys to Simple Alert or Confirm Alert, you get ElementNotSelectableException.
"selenium.common.exceptions.ElementNotSelectableException: Message: element not interactable: User dialog does not have a text box input field."
Fourth Type
Apart from these three types, there are other popups generated by web page. It is easy to handle these pop-ups as they are generated by html code and we can find it’s element locator; And do not support accept() or dismiss() methods which is only available for browser native pop-ups.
When you try to switch to alert on display of these popups, you get NoAlertPresentException. Because they are not alerts.
Alerts using Python Selenium Webdriver
The below is the sample html which can generate alerts, prompts and confirm popups; please make an html file and pass file location to the webdriver.
<html> <head> <title>Python-Selenium</title> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> div { margin: 2%; } </style> </head> <body> <div id='alert'> <button id='show-alert' onclick='alert("You got an alert!");'>Alert Me</button> </div> <div id='prompt'> <button id='show-prompt' onclick='var name=prompt("Enter your name!");document.getElementById("name").innerText=name;'>Prompt Me</button> </div> <div id='name-details'> <p>My name is <span id='name'>I don't have name!!!</span></p> </div> <div id='confirm'> <button id='show-confirm' onclick='var status=confirm("is your name correct?");if(status==true) {document.getElementById("name-confirmation").style.display="block";}'>Confirm Me</button> </div> <div id='name-confirmation' style='display: none;'> <p id='name-confirmation'>Thanks for confirming your name!!!</p> </div> <div id='modal'> <button id='open-modal' onclick="document.getElementById('modal-popup').style.display='block'" class="w3-button w3-red">Open Modal</button> </div> <div id="modal-popup" class="w3-modal"> <div class="w3-modal-content"> <div class="w3-container"> <span id='close-modal' onclick="document.getElementById('modal-popup').style.display='none'" class="w3-button w3-display-topright">×</span> <p id='modal-text'>I am a Modal popup</p> <div> <button name='close' onclick="document.getElementById('modal-popup').style.display='none'">Click to Close</button> </div> </div> </div> </div> </body> </html>
Simple Alert
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driver.get("file:///PathToHtml/index.html") driver.find_element_by_id('show-alert').click() alert = driver.switch_to.alert print(alert.text) alert.accept() driver.quit()
Confirm Alert
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driver.get("file:///PathToHtml/index.html") driver.find_element_by_id('show-confirm').click() alert = driver.switch_to_alert() print(alert.text) alert.accept() driver.find_element_by_id('show-confirm').click() alert = driver.switch_to_alert() print(alert.text) alert.dismiss() driver.quit()
Prompt Alert
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driver.get("file:///PathToHtml/index.html") driver.find_element_by_id('show-prompt').click() alert = driver.switch_to.alert print(alert.text) alert.send_keys('Alex') alert.accept() driver.find_element_by_id('show-prompt').click() alert = driver.switch_to.alert print(alert.text) alert.send_keys('Alex') alert.dismiss() driver.quit()
HTML Popups
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driver.get("file:///PathToHtml/index.html") driver.find_element_by_id('open-modal').click() print(driver.find_element_by_id('modal-text').text) driver.find_element_by_name('close').click() driver.quit()
NoAlertPresentException Demo:
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driver.get("file:///PathToHtml/index.html") driver.find_element_by_id('open-modal').click() alert = driver.switch_to_alert() print(alert.text) driver.quit()
We get below exception. Because the modal popup displayed is not an alert.
Checking for mac64 chromedriver:2.43 in cache Driver found in /Users/avelusamy/.wdm/chromedriver/2.43/mac64/chromedriver Traceback (most recent call last): File "popup.py", line 74, in alert = driver.switch_to_alert() File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 803, in switch_to_alert return self._switch_to.alert File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/switch_to.py", line 55, in alert alert.text File "/Library/Python/2.7/site-packages/selenium/webdriver/common/alert.py", line 69, in text return self.driver.execute(Command.GET_ALERT_TEXT)["value"] File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoAlertPresentException: Message: no such alert (Session info: chrome=70.0.3538.77) (Driver info: chromedriver=2.43.600229 (3fae4d0cda5334b4f533bede5a4787f7b832d052),platform=Mac OS X 10.13.6 x86_64)
Sometimes alerts are not displayed immediately. When we try to switch to alerts before it is displayed, we get NoAlertPresentException. To avoid this situation, we can wait for alerts to appear. Below sample explains how to handle this scenario.
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=ChromeDriverManager().install()) driver.get("file:///PathToHtml/index.html") driver.find_element_by_id('show-alert').click() try: WebDriverWait(driver, 5).until(EC.alert_is_present(), 'Timed out waiting for alerts to appear') alert = driver.switch_to.alert alert.accept() print("alert accepted") except TimeoutException: print("no alert")
Hope this article is informative. Please let us know your thoughts in comments.
One Response
First time visiting your website, I like it!