This script opens a page with a JavaScript alert, clicks the button to show the alert, prints the alert text, accepts the alert, then closes the browser.
Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
# Setup Chrome driver (make sure chromedriver is in PATH)
service = Service()
driver = webdriver.Chrome(service=service)
try:
driver.get('https://www.selenium.dev/documentation/webdriver/browser/alerts/')
# Click button that triggers alert
button = driver.find_element(By.XPATH, "//button[contains(text(),'Click for JS Alert')]")
button.click()
# Switch to alert and accept it
alert = driver.switch_to.alert
print('Alert text:', alert.text)
alert.accept()
time.sleep(1) # Wait to see resultfinally:
driver.quit()
OutputSuccess
Important Notes
Always switch to the alert before accepting it, or Selenium will throw an error.
If you try to accept an alert that is not present, your test will fail.
Use alert.text to check the alert message before accepting.
Summary
Use driver.switch_to.alert to access alerts.
Call accept() to click OK on the alert.
Check alert text with alert.text if needed.
Practice
(1/5)
1. What does the driver.switch_to.alert.accept() command do in Selenium Python?
easy
A. It closes the browser window.
B. It refreshes the current page.
C. It clicks the OK button on a simple alert popup.
D. It sends text input to the alert popup.
Solution
Step 1: Understand alert handling in Selenium
The driver.switch_to.alert accesses the alert popup currently shown by the browser.
Step 2: Accepting the alert
The accept() method clicks the OK button on the alert, closing it.
Final Answer:
It clicks the OK button on a simple alert popup. -> Option C
Quick Check:
accept() = clicks OK [OK]
Hint: accept() always clicks OK on alert popups [OK]
Common Mistakes:
Confusing accept() with dismiss() which clicks Cancel
Trying to send keys with accept()
Assuming accept() closes the browser
2. Which of the following is the correct syntax to accept a simple alert in Selenium Python?
easy
A. driver.alert.accept()
B. driver.switch_to.alert.accept()
C. driver.switch_to_alert.accept()
D. driver.switchTo().alert().accept()
Solution
Step 1: Recall correct Selenium Python syntax
The correct way to switch to alert is driver.switch_to.alert.
Step 2: Confirm method chaining
Calling accept() on the alert object accepts the alert.