How to handle frames in Selenium with python?


We can handle frames in Selenium. A frame is an HTML element that keeps a document within another document in a page. HTML has the <frame> or <iframe> tags for embedding a frame inside a document.

There are multiple APIs available in Selenium to work with the frames. They are listed below −

  • switch_to_frame(id)

    This method is used to identify a frame with the help of frame id and then switch the focus to that particular frame.

Syntax

driver.switch_to_frame("frameid"), where frameid is the id attribute present under the frame/iframe tag in HTML.
  • switch_to_frame(name)

    This method is used to identify a frame with the help of frame name and then switch the focus to that particular frame.

Syntax

driver.switch_to_frame("framename"), where framename is the name attribute present under the frame/iframe tag in HTML.
  • switch_to_frame(webelement)

    This method is used to identify a frame with the help of frame webelement and then switch the focus to that particular frame.

Syntax

driver.switch_to_frame("frameclassname"), where frameclassname is the name of class attribute present under the frame/iframe tag in HTML.
  • switch_to_parent_frame()

    This method is used to come out of the present frame, then we can access the elements outside that frame and not inside of that frame.

  • switch_to_default_content()

    This method is used to come out of all the frames and switch the focus at the page. Once we move out, it loses the access to the elements inside the frames in the page.

Example

Code Implementation with frames.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# to switch to frame with frame name
driver.switch_to.frame("frame-bottom")
# to get the text inside the frame and print on console
print(driver.find_element_by_xpath ("//*[text()='BOTTOM']").text)
# to move out the current frame to the page level
driver.switch_to.default_content()
#to close the browser
driver.quit()

Updated on: 29-Jul-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements