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

๐ŸŒ Web Testing

Visual Regression Testing with Percy

Real Device Testing with Appium

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Handling Frames and Iframes Using Playwright