Handle iFrames in Selenium WebDriver

An IFrame (Inline Frame) is an HTML document embedded inside another HTML document on a website. The IFrame HTML element is often used to insert content from another source, such as an advertisement, into a Web page.

An <iframe> is used for containing (X)HTML documents in other (X)HTML documents. This enables updates of parts of a website while the user browses, without making them reload the whole thing.

If name of iFrame is given then it is easy to deal with
driver.switchTo().frame("name of iframe");

But in case if name is not given then follow these steps...

First get all elements starting with 'iframe' tag in a list


List<WebElement> myL = driver.findElements(By.tagName("iframe"));  
 	

Print the size of list (so that you know that how many iframes exist on the web page)

 
System.out.println(myL.size());
  	

Use a for loop to get html code of iFrame

 
for(int i=0; i<myL.size(); i++){
       
        driver.switchTo().frame(i);                                                 
       
        System.out.println("******* iFrame + " +i + " start ***********");

        System.out.println(driver.getPageSource());          //Printing HTML code of iFrame

        System.out.println("******* iFrame + " +i + " end ***********");
       
        driver.switchTo().defaultContent();                     // Switching WebDriver to default content
    } 

  	

Once you get the your iFrame html code with frame number then switch on it using
driver.switchTo().frame(7);