0
0
Selenium Pythontesting~5 mins

Confirmation alert handling in Selenium Python

Choose your learning style9 modes available
Introduction

Confirmation alerts ask you to confirm or cancel an action on a webpage. Handling them lets your test click OK or Cancel automatically.

When a webpage asks 'Are you sure?' before deleting a file.
When confirming a form submission with a popup.
When a logout button shows a confirmation alert.
When testing canceling an action from a popup.
When automating acceptance or dismissal of browser confirmation dialogs.
Syntax
Selenium Python
alert = driver.switch_to.alert
alert.accept()  # Click OK
alert.dismiss() # Click Cancel

switch_to.alert moves focus to the alert popup.

accept() clicks OK, dismiss() clicks Cancel.

Examples
This accepts (clicks OK) on the confirmation alert.
Selenium Python
alert = driver.switch_to.alert
alert.accept()
This dismisses (clicks Cancel) on the confirmation alert.
Selenium Python
alert = driver.switch_to.alert
alert.dismiss()
Sample Program

This script opens a simple page with a button that triggers a confirmation alert. It clicks the button, switches to the alert, accepts it, and prints confirmation.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open a test page with confirmation alert
html = '''data:text/html,<html><body><button onclick="confirm('Are you sure?')">Click me</button></body></html>'''
driver.get(html)

# Click the button to open confirmation alert
button = driver.find_element(By.TAG_NAME, 'button')
button.click()

# Switch to alert and accept it
alert = driver.switch_to.alert
alert.accept()

print('Alert accepted')

# Wait a bit and close browser
time.sleep(1)
driver.quit()
OutputSuccess
Important Notes

Always switch to the alert before trying to accept or dismiss it.

If you try to accept an alert that is not present, Selenium will raise an error.

Use dismiss() to simulate clicking Cancel on the confirmation alert.

Summary

Confirmation alerts ask for user confirmation with OK or Cancel buttons.

Use driver.switch_to.alert to access the alert.

Use accept() to click OK and dismiss() to click Cancel.