What are the differences between switch_to_default_content() and switch_to.parent_frame() methods in Selenium with python?


There are differences between switch_to.parent_frame() and switch_to_default_content() in frames. They are listed below −

  • 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. Thus the control is switched; the outer part may be another frame or part of the web page. So we are able to come out of the current frame.

Syntax

driver.switch_to.parent_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.

Syntax

driver.switch_to_default_content();

Example

Code Implementation with switch_to_default_content() method.

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()

Code Implementation with switch_to_parent_frame() method.

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 parent frame name
driver.switch_to.frame("frame-top")
# to switch to frame with frame inside parent frame with name
driver.switch_to.frame("frame-left")
# to get the text inside the frame and print on console
print(driver.find_element_by_xpath ("//*[text()='LEFT']").text)
# to move out the current frame to the parent frame
driver. switch_to_parent_frame()
#to close the browser
driver.quit()

Updated on: 29-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements