Handling Alerts and Pop-ups Using Selenium Python

 While automating web applications with Selenium in Python, you’ll often encounter JavaScript alerts and pop-ups. These can interrupt your automation flow if not handled properly. Selenium provides simple and effective methods to interact with such pop-ups. This blog covers how to handle alerts, confirm dialogs, and prompt pop-ups using Selenium in Python.

Types of JavaScript Alerts

Simple Alert – Just displays a message with an “OK” button.

Confirmation Alert – Displays a message with “OK” and “Cancel” buttons.

Prompt Alert – Asks the user to enter text with “OK” and “Cancel” options.

1. Handling Simple Alert

A simple alert can be handled using the switch_to.alert method.

python

Copy

Edit

from selenium import webdriver

from selenium.webdriver.common.by import By

import time

driver = webdriver.Chrome()

driver.get("https://example.com")

# Trigger the alert

driver.find_element(By.ID, "alertButton").click()

# Switch to alert and accept it

alert = driver.switch_to.alert

print("Alert text:", alert.text)

alert.accept()

2. Handling Confirmation Alert

You can choose to accept or dismiss confirmation alerts.

python

Copy

Edit

# Trigger the confirm alert

driver.find_element(By.ID, "confirmButton").click()

alert = driver.switch_to.alert

print("Confirmation message:", alert.text)

# Accept the alert

alert.accept()

# Or dismiss it

# alert.dismiss()

3. Handling Prompt Alert

Prompt alerts allow you to send text input.

python

Copy

Edit

# Trigger the prompt

driver.find_element(By.ID, "promptButton").click()

alert = driver.switch_to.alert

print("Prompt message:", alert.text)

# Send input and accept

alert.send_keys("Selenium Test")

alert.accept()

Best Practices

Always wait for the alert to be present if it's delayed.

python

Copy

Edit

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 10).until(EC.alert_is_present())

Use try-except blocks to handle unexpected alerts.

Conclusion

Handling alerts and pop-ups is crucial for smooth test automation. Selenium’s built-in switch_to.alert method makes it easy to work with all types of JavaScript alerts in Python. Whether you’re accepting a simple alert or inputting text in a prompt, mastering these techniques will make your Selenium tests more robust and reliable.

Learn Selenium Python Training in Hyderabad

Read More:

Writing Your First Selenium Automation Script in Python

Visit our IHub Talent Training Institute

Get Direction


Comments

Popular posts from this blog

SoapUI for API Testing: A Beginner’s Guide

Automated Regression Testing with Selenium

Containerizing Java Apps with Docker and Kubernetes