Default content switching in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize the Chrome driver with webdriver.Chrome() as driver: driver.get('https://example.com/page_with_iframe') wait = WebDriverWait(driver, 10) # Wait for iframe to be available and switch to it wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'iframe1'))) # Wait for the button inside iframe and click it iframe_button = wait.until(EC.element_to_be_clickable((By.ID, 'iframe-button'))) iframe_button.click() # Switch back to default content driver.switch_to.default_content() # Wait for the main page button and click it main_button = wait.until(EC.element_to_be_clickable((By.ID, 'main-button'))) main_button.click() # Optionally, assertions can be added here if this was inside a test framework
This script uses Selenium WebDriver with Python to automate switching between an iframe and the main page.
First, it opens the target page.
Then it waits explicitly for the iframe with id 'iframe1' to be available and switches to it using frame_to_be_available_and_switch_to_it.
Inside the iframe, it waits for the button with id 'iframe-button' to be clickable and clicks it.
After that, it switches back to the main page using driver.switch_to.default_content().
Finally, it waits for the main page button with id 'main-button' to be clickable and clicks it.
Explicit waits ensure elements are ready before interaction, preventing errors.
Using By.ID is a best practice locator strategy for clarity and speed.
Now add data-driven testing to click multiple iframe buttons with different ids and verify main page button click after each