Sat. Jun 3rd, 2023

Switching to and from an iframe on a page in target and interact with elements using python is a piece of cake.

Firstly lets quickly set up our web driver (I’ll use safari in this example as it includes a built in web driver)

from selenium import webdriver
driver = webdriver.Safari()

Then visit a page which contains an iframe:

driver.get('https://www.pagewithiframe.com')

Switching to an iframe

driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

You can now start targeting element within the iframe.

Switching from an iframe

Switching back to the iframe parent is just as simple:

driver.switch_to.default_content()

Putting it all together:

# Import web driver
from selenium import webdriver

# Specify our driver
driver = webdriver.Safari()

# Visit a page
driver.get('https://www.pagewithiframe.com')

# Switch to the iframe
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

# ----------------------
# Do stuff in the iframe
# ----------------------

# Switch back to the parent
driver.switch_to.default_content()

By admin