0
0
Selenium Pythontesting~5 mins

Default content switching in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes web pages have frames or iframes. To test elements outside these frames, you need to switch back to the main page. This is called default content switching.

After working inside an iframe and you want to interact with the main page again.
When you want to reset your focus from any nested frames to the main page.
If your test navigates through multiple frames and needs to return to the top-level page.
When you want to avoid errors caused by trying to find elements outside the current frame.
Syntax
Selenium Python
driver.switch_to.default_content()

This command switches the focus back to the main page (default content).

Use it after switching into one or more iframes.

Examples
Switch into iframe named 'frame1', then switch back to main page.
Selenium Python
driver.switch_to.frame('frame1')
driver.switch_to.default_content()
Switch into the first iframe by index, then back to default content.
Selenium Python
driver.switch_to.frame(0)
driver.switch_to.default_content()
Sample Program

This script opens a page with an iframe, switches into the iframe to get its heading text, then switches back to the main page to get the main heading text. It prints both to show the switch worked.

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 sample page with iframe
driver.get('https://www.w3schools.com/html/html_iframe.asp')

# Switch to iframe by xpath
iframe = driver.find_element(By.XPATH, '//iframe[@title="W3Schools HTML Tutorial"]')
driver.switch_to.frame(iframe)

# Find element inside iframe
heading = driver.find_element(By.TAG_NAME, 'h1')
print('Inside iframe:', heading.text)

# Switch back to default content
driver.switch_to.default_content()

# Find element in main page
main_heading = driver.find_element(By.TAG_NAME, 'h1')
print('In main page:', main_heading.text)

# Close driver
driver.quit()
OutputSuccess
Important Notes

Always switch back to default content before interacting with elements outside iframes.

If you forget to switch, Selenium will throw errors like NoSuchElementException.

Summary

Use driver.switch_to.default_content() to go back to the main page from any iframe.

This helps avoid errors when your test needs to interact with elements outside frames.