Python - Selenium - Switch to iframe

By xngo on June 21, 2019

An iframe(Inline Frame) is used to embed an HTML document within the current HTML document. It is often used to insert content from another source.

Iframe causes a lot of frustration among Selenium newbies because Selenium can't the find the elements. They swear that they use the correct xpath, id, css selector or tag name. And, Selenium still can't that element.

Well, in Selenium, when a webpage contains an iframe, you have to treat it like another webpage. To access the content of the iframe, you have to switch to that iframe first.

In the code example below, we are going to navigate to https://jqueryui.com/droppable/. This webpage contains an iframe demonstrating a drag and drop example. We are going to switch to that iframe and then, from that iframe, drag and drop the square.

import time
 
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
 
from selenium.webdriver import ActionChains
 
# Create chrome driver.
driver = webdriver.Chrome()
 
# Open the webpage that contains iframe.
driver.get("http://jqueryui.com/droppable/")
 
# Pause for 3 seconds for you to see the initial state.
time.sleep(3)
 
 
# Wait for iframe to load and switch to it.
############################################
WebDriverWait(driver, 5).until(
            EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, ".demo-frame"))
        )
 
# In the iframe, drag item to target item.
##############################################
drag_item = driver.find_element_by_id("draggable")
target_item = driver.find_element_by_id("droppable")
 
action_chains = ActionChains(driver)
action_chains.drag_and_drop(drag_item, target_item).perform()
 
# Switch back to the main frame.
##################################
driver.switch_to_default_content()
 
 
# Pause for 10 seconds so that you can see the results.
time.sleep(10)
 
# Close.
driver.close()

Here is a video showing the code above in action.

Video showing Selenium switching iframe and drag and drop an object

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.