How to Handle Popups in Selenium
๐ 1. JavaScript Alerts, Confirms, and Prompts
These are browser-native popups that Selenium can directly interact with.
๐ Code Example (Python)
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://example.com")
# Trigger the alert
driver.find_element(By.ID, "trigger-alert").click()
# Switch to the alert
alert = driver.switch_to.alert
# Accept the alert
alert.accept()
# Dismiss the alert (if it's a confirm box)
# alert.dismiss()
# Get text from the alert
# print(alert.text)
# Send keys (if it's a prompt)
# alert.send_keys("Test input")
# alert.accept()
๐ 2. Authentication Popups (Basic Auth)
These use browser dialogs to ask for credentials (e.g., HTTP Basic Auth). Selenium can't interact with them directly, but you can bypass using the URL:
๐ Code Example:
python
Copy
Edit
driver.get("https://username:password@your-site.com")
๐ 3. HTML/CSS-Based Modals or Popups
These are regular DOM elements styled as popups using CSS/JavaScript (e.g., Bootstrap modals). You interact with them just like any web element:
๐ Code Example:
python
Copy
Edit
# Wait for the modal to appear
WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "modal-id"))
)
# Click a button inside the modal
driver.find_element(By.ID, "modal-close-button").click()
Requires:
python
Copy
Edit
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
๐งจ 4. File Upload/Download Popups
Uploads: Use send_keys() on the <input type="file"> field.
Downloads: Configure the browser to auto-download files to a predefined directory (can't interact with native file download popups).
๐ Upload Example:
python
Copy
Edit
file_input = driver.find_element(By.ID, "file-upload")
file_input.send_keys("/path/to/your/file.txt")
❌ 5. OS-Level Dialogs (e.g., Windows dialogs)
Selenium cannot handle OS-level popups. Use tools like:
AutoIt (Windows)
PyAutoGUI (Python)
Robot Framework or Winium (for advanced automation)
๐ก Tips for Stability
Always wait for popups using WebDriverWait.
Use try-except blocks to catch NoAlertPresentException for unexpected alerts.
Use explicit waits over time.sleep() to avoid flaky tests.
Learn Testing Tools Training in Hyderabad
Read More
Responsive Testing with BrowserStack
Visual Regression Testing with Percy
Real Device Testing with Appium
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment