Switch to Alert

Example site: https://demo.automationtesting.in/Alerts.html

using driver.switch_to

import time
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://demo.automationtesting.in/Alerts.html")

alert_button = driver.find_element(By.XPATH, '//button[@onclick="alertbox()"]')
alert_button.click()

# switching to the alert
alert1 = driver.switch_to.alert
print(alert1.text)
alert1.accept()

time.sleep(5)


alert_button2 = driver.find_element(By.XPATH, '//a[text()="Alert with OK & Cancel "]')
alert_button2.click()


driver.find_element(By.XPATH, '//button[@onclick="confirmbox()"]').click()

time.sleep(3)

# handle second alert
alert2 = driver.switch_to.alert
alert2.accept()
driver.quit()

using the alert class

import time
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://demo.automationtesting.in/Alerts.html")

alert_button = driver.find_element(By.XPATH, '//button[@onclick="alertbox()"]')
alert_button.click()

# handle first alert
alert = Alert(driver)
print(alert.text)
time.sleep(3)
alert.accept()

time.sleep(5)


alert_button2 = driver.find_element(By.XPATH, '//a[text()="Alert with OK & Cancel "]')
alert_button2.click()


driver.find_element(By.XPATH, '//button[@onclick="confirmbox()"]').click()

time.sleep(3)

# handle second alert
print(alert.text)
time.sleep(3)
alert.accept()

driver.quit()
Updated on