Handle Frame in Selenium Python

Profile picture for user arilio666

The switch_to.frame() method in Selenium with Python may handle frames (or iframes). This function allows you to direct WebDriver's focus to a specific frame on a web page. You can interact with the elements within the frame after you switch to it.

Frames are a shell for a webpage that contains contents within this shell. To access its content, we need to breach the outer shell.

Handle Frame in Selenium Python
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.maximize_window()
driver.get('http://www.maths.surrey.ac.uk/explore/nigelspages/frame2.htm')

frame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//frame[@src='message.htm']")))

driver.switch_to.frame(frame)
nameTab = driver.find_element(By.XPATH,"//input[@name='name']")
nameTab.send_keys("Monkey.D.Luffy")
print(nameTab.text)
driver.switch_to.default_content()
driver.quit()
  • In the above example, we begin by opening a web page with webdriver.Chrome() (assuming Chrome WebDriver is installed).
  • We then use WebDriverWait and the desired criteria (EC.presence_of_element_located) to wait for the frame to become accessible.
  • When the frame is ready, we switch to it using driver.switch_to.frame(frame), where the frame is an element of the frame.
  • After engaging with the items within the frame, you can use the driver to return to the default content.switch_to.default_content().
  • This enables you to interact with elements outside of the frame.
  • Finally, remember to use the driver to close the driver.quit().