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.
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()