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 NoAlertPresentException, TimeoutException
# Setup WebDriver (assumes chromedriver is in PATH)
driver = webdriver.Chrome()
try:
driver.get('https://example.com/form')
# Enter username
username_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'username'))
)
username_input.send_keys('testuser')
# Click submit button
submit_button = driver.find_element(By.ID, 'submit-btn')
submit_button.click()
# Wait for alert and accept it if present
try:
WebDriverWait(driver, 5).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert.accept()
except TimeoutException:
# No alert appeared, continue
pass
# Verify URL changed to success page
WebDriverWait(driver, 10).until(
EC.url_to_be('https://example.com/form-success')
)
assert driver.current_url == 'https://example.com/form-success', f"Expected URL to be 'https://example.com/form-success' but got {driver.current_url}"
finally:
driver.quit()This script opens the form page and waits for the username input to appear before typing 'testuser'. It then clicks the submit button. After clicking, it waits up to 5 seconds for an alert to appear. If the alert appears, it accepts it to prevent the test from failing due to unhandled alert. If no alert appears, it continues without error. Finally, it waits for the URL to change to the success page and asserts this change. The use of explicit waits ensures the script waits only as long as needed, avoiding fixed delays. The try-except block for alert handling prevents test failure if no alert is present.