i

Selenium Step By Step Guide

Handling Iframes

What is an Iframe?

An Iframe is an HTML tag which stays inside an HTML document. Most of the time it seems like the element is present on a web page as usual but if element is under Iframe then we can not directly locate the element until we have switched to that Iframe. We can see how an Iframe looks like inside the HTML document.

 

 

 

 

 

 So its clear that we need to first switch driver control to the Iframe and then further actions can be done as a normal web page.

Different ways to switch to an Iframe:

In order to switch to an Iframe we need to use “driver.switchTo.frame(%switchParameter%)”. Here frame() method takes an argument to switch to the Iframe in three different ways:

  1. the frame(WebElement element): Passing Iframe element.
  2. the frame(int index): Passing the index at which Iframe is placed.
  3. the frame(String idOrName): Passing Iframe ID or name as a String.

Let us see the sample code for each way to switch over an Iframe window:

WebElement ele= driver.findElement(By.xpath(xpathString));

Using Iframe WebElement:

driver.switchTo().frame(ele);

Using Iframe Index number:

driver.switchTo().frame(0);

Using Iframe name:

driver.switchTo().frame(“frameFirst”);

Using Iframe ID:

driver.switchTo().frame(“if1”);//String:Using frame ID

Once we have switched over an Iframe then we can perform normal Selenium actions like click(), getText(), sendKeys() and so many on the elements present inside that Iframe.

Switching to another Frame:

When we need to switch to any other Iframe while we are already dealing with one, first, we need to switch the control to the base page and then switch to another frame.

Let us say we are on FrameFirst and want to switch to FrameSecond, then first, we need to go back to the base page by using "driver.switchTo().defaultContent()” command.

Once we land to the base page, we can switch to FrameSecond as we have switched to FrameFirst.

driver.switchTo().defaultContent();

driver.switchTo().frame(“FrameSecond”);

This way the control gets switched to second frame and now we can perform normal WebElement actions on the elements present on Second frame.