Handling Alerts, Pop-ups, and iFrames in Selenium with Python

 H

Handling Alerts, Pop-ups, and iFrames in Selenium with Python

๐Ÿ”” 1. Handling Alerts

JavaScript alerts are simple pop-ups that require user interaction. Selenium provides switch_to.alert for this.


Example:

python

Copy

Edit

from selenium import webdriver

from selenium.webdriver.common.by import By

import time


driver = webdriver.Chrome()

driver.get("https://example.com/alert")


# Trigger the alert (e.g., clicking a button that opens it)

driver.find_element(By.ID, "alertButton").click()


# Switch to alert

alert = driver.switch_to.alert


# Accept the alert

alert.accept()


# Or to dismiss:

# alert.dismiss()


# Or to get the alert text:

# print(alert.text)


# Or to send text (for prompt alerts):

# alert.send_keys("Your input")


driver.quit()

๐Ÿ’ฌ 2. Handling Pop-ups (Browser Windows/Tabs)

Sometimes pop-ups are separate windows or tabs. You can manage them by switching between window handles.


Example:

python

Copy

Edit

driver = webdriver.Chrome()

driver.get("https://example.com/popup")


# Store the main window handle

main_window = driver.current_window_handle


# Trigger the pop-up

driver.find_element(By.ID, "popupButton").click()


# Wait for new window

time.sleep(2)


# Get all window handles

all_windows = driver.window_handles


# Switch to the new window

for window in all_windows:

    if window != main_window:

        driver.switch_to.window(window)

        break


# Do something in the pop-up window

print(driver.title)


# Close the pop-up and return to the main window

driver.close()

driver.switch_to.window(main_window)

๐Ÿ–ผ️ 3. Handling iFrames

If the element you want to interact with is inside an <iframe>, you need to switch to it first.


Example:

python

Copy

Edit

driver = webdriver.Chrome()

driver.get("https://example.com/iframe")


# Switch to the iframe using its name, ID, index, or WebElement

driver.switch_to.frame("iframe_id")


# Interact with elements inside the iframe

driver.find_element(By.ID, "insideFrameButton").click()


# Return to the main content

driver.switch_to.default_content()

✅ Tips

Always wait for elements to appear using WebDriverWait for better stability.


Use try-except to handle unexpected alerts or missing elements.


Close pop-up windows properly to avoid resource leaks.


Would you like a downloadable script or test case examples for practice?

Learn Selenium Python Training in Hyderabad

Read More

Handling Input Boxes, Buttons, and Checkboxes in Selenium

Working with Browser Navigation in Selenium using Python

Visit Our Quality Thought Training in Hyderabad

Get Directions




Comments

Popular posts from this blog

Entry-Level Cybersecurity Jobs You Can Apply For Today

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners