Web pages often have sections called iFrames that load separate content. To test elements inside these iFrames, you must switch your focus to them first.
0
0
iFrame switching (switch_to.frame) in Selenium Python
Introduction
When a button or input is inside an iFrame and you want to click or type in it.
When you need to verify text or elements that are loaded inside an iFrame.
When automating form filling inside an embedded frame on a webpage.
When a webpage has ads or widgets inside iFrames and you want to interact with them.
When you want to switch back and forth between main page and iFrame content during a test.
Syntax
Selenium Python
driver.switch_to.frame(frame_reference)
frame_reference can be the frame's name, index (number), or a WebElement.
Always switch back to the main page using driver.switch_to.default_content() after working inside an iFrame.
Examples
Switch to an iFrame by its name attribute.
Selenium Python
driver.switch_to.frame('frameName')Switch to the first iFrame on the page by index (starting at 0).
Selenium Python
driver.switch_to.frame(0)Find the iFrame as a WebElement and switch to it.
Selenium Python
iframe_element = driver.find_element(By.CSS_SELECTOR, 'iframe.someClass')
driver.switch_to.frame(iframe_element)Sample Program
This script opens a webpage with an iFrame, switches into the iFrame, prints the heading inside it, then switches back and prints the main page title.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup driver (make sure chromedriver is in PATH) driver = webdriver.Chrome() # Open a page with an iFrame driver.get('https://www.w3schools.com/html/html_iframe.asp') # Wait for page to load time.sleep(2) # Switch to the iFrame by CSS selector iframe = driver.find_element(By.CSS_SELECTOR, 'iframe[src="default.asp"]') driver.switch_to.frame(iframe) # Find heading inside iFrame and print text heading = driver.find_element(By.TAG_NAME, 'h1') print(heading.text) # Switch back to main page driver.switch_to.default_content() # Print title of main page print(driver.title) driver.quit()
OutputSuccess
Important Notes
Always wait or ensure the iFrame is loaded before switching to it to avoid errors.
Switching to an iFrame changes the context for finding elements; elements outside the iFrame won't be found until you switch back.
Summary
Use driver.switch_to.frame() to focus on iFrame content.
You can switch by name, index, or WebElement.
Remember to switch back to the main page with driver.switch_to.default_content().