0
0
Selenium Pythontesting~5 mins

Why alert handling prevents test failures in Selenium Python

Choose your learning style9 modes available
Introduction

Alert handling helps your test keep running smoothly by managing pop-up messages that can stop the test if ignored.

When a website shows a pop-up alert asking for confirmation.
When a form submission triggers a browser alert.
When unexpected alerts appear during navigation.
When testing features that use JavaScript alerts or prompts.
When you want to avoid test crashes caused by unhandled alerts.
Syntax
Selenium Python
alert = driver.switch_to.alert
alert.accept()  # To click OK
alert.dismiss()  # To click Cancel
Use driver.switch_to.alert to access the alert box.
Use accept() to confirm and dismiss() to cancel the alert.
Examples
This accepts (clicks OK) on the alert box.
Selenium Python
alert = driver.switch_to.alert
alert.accept()
This dismisses (clicks Cancel) on the alert box.
Selenium Python
alert = driver.switch_to.alert
alert.dismiss()
This reads the alert message text before accepting it.
Selenium Python
alert = driver.switch_to.alert
text = alert.text
alert.accept()
Sample Program

This test opens a page with a button that triggers an alert. It switches to the alert, reads its text, accepts it, and prints confirmation. Handling the alert prevents the test from failing due to the pop-up.

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

# Setup driver
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
driver = webdriver.Chrome(options=options)

try:
    driver.get('https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert')
    driver.switch_to.frame('iframeResult')

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

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

    print(f'Alert text was: {alert_text}')
    print('Alert accepted successfully.')

except Exception as e:
    print(f'Test failed due to: {e}')

finally:
    driver.quit()
OutputSuccess
Important Notes

Always handle alerts immediately after they appear to avoid test interruptions.

Use try-except blocks to catch unexpected alerts and handle them gracefully.

Switching to the alert is necessary before interacting with it.

Summary

Alerts can stop tests if not handled.

Use driver.switch_to.alert to manage alerts.

Accept or dismiss alerts to keep tests running smoothly.