from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# Initialize the WebDriver (e.g., Chrome)
driver = webdriver.Chrome()
try:
driver.get('https://example.com/alert') # Replace with actual URL
# Locate the button that triggers the alert
alert_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, 'alertButton'))
)
# Click the button to open the alert
alert_button.click()
# Wait for the alert to be present
WebDriverWait(driver, 10).until(EC.alert_is_present())
# Switch to the alert
alert = driver.switch_to.alert
# Assert alert text is not empty (optional check)
assert alert.text != '', 'Alert text should not be empty'
# Accept the alert
alert.accept()
# Verify alert is no longer present
try:
WebDriverWait(driver, 3).until(EC.alert_is_present())
alert_present = True
except TimeoutException:
alert_present = False
assert not alert_present, 'Alert should be closed after acceptance'
finally:
driver.quit()This script starts by opening the browser and navigating to the page with the alert button.
It waits explicitly for the alert button to be clickable, then clicks it to trigger the alert popup.
Next, it waits for the alert to appear using an explicit wait, then switches to the alert using Selenium's Alert API.
It asserts that the alert text is not empty to confirm the alert is present.
Then it accepts the alert to close it.
Finally, it verifies that the alert is no longer present by waiting briefly and catching a timeout exception if no alert appears.
The driver quits at the end to close the browser.