Select iframe using Python and Selenium

SeleniumAutomation TestingTesting Tools

We can select iframe with Selenium webdriver. An iframe is identified with a <iframe> tag in an html document. An iframe is an html document containing elements which resides inside another html document.

Let us see a 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 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 webelement is put as an argument to the method.

    Syntax−

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

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

    Syntax−

    driver.switch_to.default_content()

Example

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 element and get text method
s = driver.find_element_by_xpath("//body").text
print ("Test inside frame: " + s)
# move out of frame to parent page
driver.switch_to.default_content()
driver.quit()

Output

raja
Published on 18-Sep-2020 11:29:54
Advertisements