In this article, we explored how to handle different types of JavaScript popups — alerts, confirm boxes, and prompt boxes — using Selenium. Each popup requires immediate user interaction and can be managed with driver.switch_to.alert. We used methods like accept(), dismiss(), and send_keys() to interact with these dialogs.
- Create a sample HTML. file to see the implementation of Handling popups and alerts.
Alerts and Popups Demo
Alerts and Popups Demo
2. Create a Python file and start by importing the libraries and creating. an instance of the Chrome Driver.

3. Next copy the URL of the HTML file.

3. Handling the Alert.

alert.accept(): Accepts the alert (clicks ‘OK’).
find_element(By.XPATH, “//button[text()=’Show Alert’]”): Locates the button using XPath and clicks it.
switch_to.alert: Switches the context to the alert popup.
alert.text: Retrieves the text of the alert.
4. Handling the Confirm

- Locates the button by using the Xpath and clicks on it
- Switches the focus to the confirm box.
- Prints the message displayed in the confirm box.
- Accepts the confirm box and waited for 2 sec.
5. Handling a Prompt Box

- Locates the button by using the Xpath and clicks on it
- Switches the focus to the prompt box.
- Prints the message displayed in the prompt box.
- Enters the text “Alice” into the prompt’s input field.
- Accepts the confirm box and waited for 2 sec.
- Clicks “OK” on the prompt box and waited for 2 sec.
6. Exception Handling

In case of any Error it prints the error message and finally closes the browser.
Final code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
import time
# Initialize WebDriver and open the HTML file
driver = webdriver.Chrome()
driver.get("http://127.0.0.1:5500/alerts.html")
try:
# Handle Alert Box
print("Handling Alert Box...")
driver.find_element(By.XPATH, "//button[text()='Show Alert']").click()
alert = Alert(driver) # Switch to the alert
print("Alert Text:", alert.text) # Print alert text
alert.accept() # Accept the alert
time.sleep(2) # Pause to observe the result
# Handle Confirm Box
print("Handling Confirm Box...")
driver.find_element(By.XPATH, "//button[text()='Show Confirm']").click()
confirm = Alert(driver) # Switch to the confirm box
print("Confirm Text:", confirm.text)
confirm.accept() # Accept the confirm box (you can also use dismiss() to cancel)
time.sleep(2) # Pause to observe the result
# Handle Prompt Box
print("Handling Prompt Box...")
driver.find_element(By.XPATH, "//button[text()='Show Prompt']").click()
prompt = Alert(driver) # Switch to the prompt box
print("Prompt Text:", prompt.text)
prompt.send_keys("Alice") # Enter text into the prompt box
prompt.accept() # Accept the prompt
time.sleep(2) # Pause to observe the result
except Exception as e:
print("Error:", e)
finally:
# Close the browser
driver.quit()
Output

With this you have understand how to handle alerts and pop-up