0
0
Selenium Pythontesting~5 mins

Simple alert acceptance in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes websites show small pop-up messages called alerts. We need to click OK on these alerts to continue testing.

When a website shows a pop-up alert after clicking a button.
When testing confirmation messages that require clicking OK.
When an alert blocks further actions until accepted.
When automating form submissions that trigger alerts.
When verifying alert text before accepting it.
Syntax
Selenium Python
alert = driver.switch_to.alert
alert.accept()

driver.switch_to.alert lets you access the alert box.

accept() clicks the OK button on the alert.

Examples
Basic way to accept a simple alert.
Selenium Python
alert = driver.switch_to.alert
alert.accept()
Print the alert message before accepting it.
Selenium Python
alert = driver.switch_to.alert
print(alert.text)
alert.accept()
Sample Program

This script opens a page with a JavaScript alert, clicks the button to show the alert, prints the alert text, accepts the alert, then closes the browser.

Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time

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

try:
    driver.get('https://www.selenium.dev/documentation/webdriver/browser/alerts/')
    
    # Click button that triggers alert
    button = driver.find_element(By.XPATH, "//button[contains(text(),'Click for JS Alert')]")
    button.click()
    
    # Switch to alert and accept it
    alert = driver.switch_to.alert
    print('Alert text:', alert.text)
    alert.accept()
    
    time.sleep(1)  # Wait to see result
finally:
    driver.quit()
OutputSuccess
Important Notes

Always switch to the alert before accepting it, or Selenium will throw an error.

If you try to accept an alert that is not present, your test will fail.

Use alert.text to check the alert message before accepting.

Summary

Use driver.switch_to.alert to access alerts.

Call accept() to click OK on the alert.

Check alert text with alert.text if needed.