In this article, we will explore how to handle different types of JavaScript popups — alerts, confirm boxes, and prompt boxes — using Selenium. Each popup requires immediate user interaction and can be managed with driver.switch_to.alert. We will use methods like accept(), dismiss(), and send_keys() to interact with these.
Follow the below steps to implement this.
- Create a sample HTML. file to see the implementation of Handling popups and alerts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Alerts and Popups Demo</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding-top: 50px; }
button { margin: 10px; padding: 10px 20px; font-size: 16px; }
</style>
<script>
function showAlert() {
alert("This is a simple alert box!");
}
function showConfirm() {
let result = confirm("Do you want to proceed?");
if (result) {
document.getElementById("confirm-result").innerText = "You clicked OK!";
} else {
document.getElementById("confirm-result").innerText = "You clicked Cancel!";
}
}
function showPrompt() {
let name = prompt("Please enter your name:", "John Doe");
if (name !== null && name !== "") {
document.getElementById("prompt-result").innerText = "Hello, " + name + "!";
} else {
document.getElementById("prompt-result").innerText = "No name entered.";
}
}
</script>
</head>
<body>
<h1>Alerts and Popups Demo</h1>
<button onclick="showAlert()">Show Alert</button>
<br>
<button onclick="showConfirm()">Show Confirm</button>
<p id="confirm-result"></p>
<button onclick="showPrompt()">Show Prompt</button>
<p id="prompt-result"></p>
</body>
</html>
Create a Python file.
1. Start by importing the libraries and created an instance of the Chrome Driver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
import time
# Initialize WebDriver and open the HTML file
driver = webdriver.Chrome()
2. Next copy the URL of the HTML file
driver.get("http://127.0.0.1:5500/alerts.html")
3. Handling the Alert.
try:
# Handle Alert Box
print("Handling Alert Box...")
driver.find_element(By.XPATH, "//button[text()='Show Alert']").click()
alert = Alert(driver) # Switch to the alert
print("Alert Text:", alert.text) # Print alert text
alert.accept() # Accept the alert
time.sleep(2) # Pause to observe the result
- find_element(By.XPATH, “//button[text()=’Show Alert’]”): Locates the button using XPath and clicks it.
- switch_to.alert: Switches the context to the alert popup.
- alert.text: Retrieves the text of the alert.
- alert.accept(): Accepts the alert (clicks ‘OK’).
4. Handling the Confirm
# Handle Confirm Box
print("Handling Confirm Box...")
driver.find_element(By.XPATH, "//button[text()='Show Confirm']").click()
confirm = Alert(driver) # Switch to the confirm box
print("Confirm Text:", confirm.text)
confirm.accept() # Accept the confirm box (you can also use dismiss() to cancel)
time.sleep(2) # Pause to observe the result
- Locates the button by using the Xpath and clicks on it
- Switches the focus to the confirm box.
- Prints the message displayed in the confirm box.
- Accepts the confirm box and waited for 2 sec.
5. Handling a Prompt Box
# Handle Prompt Box
print("Handling Prompt Box...")
driver.find_element(By.XPATH, "//button[text()='Show Prompt']").click()
prompt = Alert(driver) # Switch to the prompt box
print("Prompt Text:", prompt.text)
prompt.send_keys("Alice") # Enter text into the prompt box
prompt.accept() # Accept the prompt
time.sleep(2) # Pause to observe the result
- Locates the button by using the Xpath and clicks on it
- Switches the focus to the prompt box.
- Prints the message displayed in the prompt box.
- Enters the text “Alice” into the prompt’s input field.
- Accepts the confirm box and waited for 2 sec.
- Clicks “OK” on the prompt box and waited for 2 sec.
6. Exception Handling
except Exception as e:
print("Error:", e)
finally:
# Close the browser
driver.quit()
In case of any Error it prints the error message and finally closes the browser.
Final Code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
import time
# Initialize WebDriver and open the HTML file
driver = webdriver.Chrome()
driver.get("http://127.0.0.1:5500/alerts.html")
try:
# Handle Alert Box
print("Handling Alert Box...")
driver.find_element(By.XPATH, "//button[text()='Show Alert']").click()
alert = Alert(driver) # Switch to the alert
print("Alert Text:", alert.text) # Print alert text
alert.accept() # Accept the alert
time.sleep(2) # Pause to observe the result
# Handle Confirm Box
print("Handling Confirm Box...")
driver.find_element(By.XPATH, "//button[text()='Show Confirm']").click()
confirm = Alert(driver) # Switch to the confirm box
print("Confirm Text:", confirm.text)
confirm.accept() # Accept the confirm box (you can also use dismiss() to cancel)
time.sleep(2) # Pause to observe the result
# Handle Prompt Box
print("Handling Prompt Box...")
driver.find_element(By.XPATH, "//button[text()='Show Prompt']").click()
prompt = Alert(driver) # Switch to the prompt box
print("Prompt Text:", prompt.text)
prompt.send_keys("Alice") # Enter text into the prompt box
prompt.accept() # Accept the prompt
time.sleep(2) # Pause to observe the result
except Exception as e:
print("Error:", e)
finally:
# Close the browser
driver.quit()
With this you have understand how to Handle Alerts and Popups.
Output
Similar Posts
Installing Selenium and Configuring Web Driver
Locating Strategies in Selenium : Locating by Id