TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Handle Alert & Pop-up Boxes in Selenium Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python SeleniumPython Tutorials

How to Handle Alert & Pop-up Boxes in Selenium Python

Last updated: Sep 28, 2023 7:03 pm
By Meenakshi Agarwal
Share
10 Min Read
Handle Alert & Popup Boxes using Selenium Python
Handle Alert & Popup Boxes using Selenium Python
SHARE

In the Selenium Python tutorial series, we’ll learn to handle alert and pop-up boxes on a web page. It is usually a standard practice for web applications to display alert messages for confirming a user action. An Alert is a pop-up window. It gets triggered due to some action performed by the user or automatically due to some system settings.

Contents
Introduction – Handle Alert & Popup BoxesHandling a Simple AlertHandling a Confirmation AlertHandling a Prompt Alert

The purpose of alerts is to give some information to the user (it can be a warning also), take permission from the user, or take some input from the user. Click here to Go Back to the main Selenium Python tutorial.

Handle Alert & Pop-up Boxes in Selenium Python

We can broadly categorize the Alerts into the following three types.

i) Simple Alert
ii) A Confirmation Alert
iii) Prompt Alert

We will now discuss how to handle the above three types of alerts in detail.

Introduction – Handle Alert & Popup Boxes

Whenever an Alert gets triggered, and a pop-up appears on the web page. The control remains with the parent web page only. So the first task for the Selenium Webdriver is to switch the focus from the parent page to the Alert pop-up. It can be done using the following code snippet.

alert_obj = driver.switch_to.alert

After the control has moved to the Alert pop-up, we can do different actions on it using the recommended methods which are as follows.

  • alert_obj.accept() – used to accept the Alert
  • alert_obj.dismiss() – used to cancel the Alert
  • alert.send_keys() – used to enter a value in the Alert text box.
  • alert.text() – used to retrieve the message included in the Alert pop-up.

Handling a Simple Alert

A Simple Alert has a message on it and an ‘OK’ button. When it pops up, a user clicks on the ‘OK’ button to accept it.

Here is the HTML code that will generate a Simple Alert at the click of the ‘Create Alert’ button on the main page.

<!DOCTYPE html>
<html>
<body bgcolor="#C0C0C0">
<h1>
Simple Alert Demonstration</h1>
<p>
click the Below Button to create an Alert</p>
<button onclick="alertFunction()" name ="alert"> Create Alert</button>
<script>
function alertFunction() {
 alert("Hi!, I am a Simple Alert. Please Click on the 'OK' Button.");
}
</script>
</body>
</html>

You need to copy the above HTML code and save it as “Simple_Alert.HTML.”

Handle Alert # Simple Popup Box
Handle Alert # Simple Popup Box

Following is the code snippet to handle Simple Alert.

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.maximize_window()
location = "file://<Specify Path to Simple_Alert.HTML>"
driver.get(location)

#Click on the "Alert" button to generate the Simple Alert
button = driver.find_element_by_name('alert')
button.click()

#Switch the control to the Alert window
obj = driver.switch_to.alert

#Retrieve the message on the Alert window
msg=obj.text
print ("Alert shows following message: "+ msg )

time.sleep(2)

#use the accept() method to accept the alert
obj.accept()

print(" Clicked on the OK Button in the Alert Window")

driver.close

The above code simulates a Simple Alert and then switches the control to the Alert window. After that, it verifies the message in the Alert window and accepts it.

Handling a Confirmation Alert

It is similar to Simple Alert. Just that it has an extra ‘Cancel’ button to dismiss the Alert if required.

The following HTML code will generate a Confirmation Alert.

<!DOCTYPE html>
<html>
<body bgcolor="#C0C0C0">
<h1>
Confirmation Alert Demonstration</h1>
<p>
click the Below Button to create an Alert</p>
<button onclick="alertFunction()" name ="alert"> Create Alert</button>
<p id ="msg"> 
</p>
<script>
function alertFunction() {
 var txt;
 if (confirm("Hi!! I am Confirmation Alert.")) {
 
 txt = "You pressed OK!"

} else {

txt = "You pressed CANCEL!"
 }
 document.getElementById("msg").innerHTML = txt;
}
</script>
</body>
</html>

I have saved this file on my local desktop with the name ‘Confirmation_Alert.HTML.’

Handle Alert # Confirmation Popup Box
Handle Alert # Confirmation Popup Box

Here is the code to handle the Confirmation Alert.

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.maximize_window()
location = "file://<Specify Path to Confirmation_Alert.HTML>"
driver.get(location)

#Click on the "Alert" button to generate the Confirmation Alert
button = driver.find_element_by_name('alert')
button.click()

#Switch the control to the Alert window
obj = driver.switch_to.alert

#Retrieve the message on the Alert window
message=obj.text
print ("Alert shows following message: "+ message )

time.sleep(2)

#Section 1
#use the accept() method to accept the alert
obj.accept()

#get the text returned when OK Button is clicked.
txt = driver.find_element_by_id('msg')
print(txt.text)

time.sleep(2)

#refresh the webpage
driver.refresh()

# Section 2
# Re-generate the Confirmation Alert
button = driver.find_element_by_name('alert')
button.click()

time.sleep(2)

#Switch the control to the Alert window
obj = driver.switch_to.alert

# Dismiss the Alert using
obj.dismiss()

#get the text returned when Cancel Button is clicked.
txt = driver.find_element_by_id('msg')
print(txt.text)

driver.close

Let’s now summarize the steps mentioned in the above code.

  • First of all, save the above HTML code under the name ‘Confirmation_Alert.HTML’ in the machine.
  • We have to specify the above path in the placeholder defined in the Webdriver code to handle the Confirmation alert.
  • Now in Section 1 of the code, we click on the ‘OK’ button to accept the alert. After that, we printed the return message displayed on the screen.
  • In Section 2 of the code, we open the Confirmation alert one more time. This time we click on the ‘Cancel’ button to dismiss the alert box. After that, we printed the return message displayed on the screen.

Handling a Prompt Alert

It is also similar to the first two alerts. The only difference is that Prompt allows us to enter some text through it.

Following is the HTML code that will generate a Prompt alert.

<!DOCTYPE html>
<html>
<body bgcolor="#E6E6FA">
<h1>
Employee Login</h1>
<button onclick="myFunction()"name ="employeeLogin">Continue</button>

<p id="msg">
</p>
<script>
function myFunction() {
 var login = prompt("Please re-enter your name", "xxxxxx");
 
 if (login != null) {
 document.getElementById("msg").innerHTML =
 "Welcome " + login + "!! How can I help you?";
 alert("You have logged in successfully !!")
 }
}
</script>
</body>
</html>

You need to save this file as ‘Prompt_Alert.HTML.’ It is simple to handle this alert too. After shifting the focus to alert, we can enter the text into it using the send_keys() method.

Handle Alert # Prompt Popup Box
Handle Alert # Prompt Popup Box

Here is the complete code for the same.

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.maximize_window()
location = "file://<Specify Path to Prompt_Alert.HTML>"
driver.get(location)

#Click on the "employeeLogin" button to generate the Prompt Alert
button = driver.find_element_by_name('continue')
button.click()

#Switch the control to the Alert window
obj = driver.switch_to.alert

time.sleep(2)

#Enter text into the Alert using send_keys()
obj.send_keys('Meenakshi')

time.sleep(2)

#use the accept() method to accept the alert
obj.accept()

#Retrieve the message on the Alert window
message=obj.text
print ("Alert shows following message: "+ message )

time.sleep(2)

obj.accept()

#get the text returned when OK Button is clicked.
txt = driver.find_element_by_id('msg')
print(txt.text)

driver.close

Let’s look at the code in detail.

  • First of all, save the HTML code to create the Prompt Alert with the name ‘Prompt_Alert.HTML’ on your machine.
  • You have to give the path of this file in the placeholder provided in the code. You must use a forward slash while specifying the URL of the web page. Otherwise, it may not work accurately.

For example, here I have to give the path of the file as.

location = "file://C:\Users/Automation-Dev/Desktop/Meenakshi/Selenium Python/Prompt_Alert.HTML
  • After you move the control to the alert using <driver.switch_to.alert>, use the “send_keys()” method to enter the text in the alert window.

Quick Wrapup – Handle Alert & Popup Boxes

It is vital to understand how to handle alerts and popup boxes using Selenium Python. You can apply the above techniques to solve real-time use cases in your projects.

For more updates on Selenium Python tutorials, do follow our social media accounts and share this with your friends.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Switch Between IFrames Selenium Python How to Switch Between IFrames Using Selenium Python
Next Article User Acceptance Testing An Expert Guide to User Acceptance Testing

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x