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.
Practice
(1/5)
1. What is the correct method to accept a confirmation alert in Selenium with Python?
easy
A. driver.confirm.accept()
B. driver.switch_to.alert.dismiss()
C. driver.switch_to.alert.accept()
D. driver.alert.accept()
Solution
Step 1: Switch to the alert
Use driver.switch_to.alert to access the alert popup.