How to handle frames in Selenium Webdriver in Python?

Rest AssuredSelenium Web DriverDynamic Programming

We can handle frames in Selenium webdriver in Python. An iframe is identified with a <iframe> tag in an html document. An iframe is an html document containing elements that reside inside another html document. Let us see an html document of a frame.

The following methods help to switch between iframes −

  • switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of the iframe is 0.

    Syntax

    driver.switch_to.frame(0), switching to the first iframe.

  • switch_to.frame(args) - The frame name or id is put as an argument to the method.

    Syntax

    driver.switch_to.frame("nm"), switching to the iframe with name nm.

  • switch_to.frame(args) - The frame web element is put as an argument to the method.

    Syntax

    driver.switch_to.frame(f), switching to the iframe with web elements f.

  • switch_to.default_content() – To shift to the parent page from the iframe.

    Syntax

    driver.switch_to.default_content()

Example

Code Implementation.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://the-internet.herokuapp.com")
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# switch to frame with name
driver.switch_to.frame("frame-bottom")
# identify the element and get text method
s = driver.find_element_by_xpath("//body").text
print ("Test inside frame: " + s)
# move out of frame to the parent page
driver.switch_to.default_content()
driver.quit()

Output

raja
Published on 22-Nov-2021 11:21:12
Advertisements