Handling iFrames in Selenium Based Test Automation

How To Identify iFrames on a Web Page?

int iFrameSize = driver.findElements(By.tagName("iframe")).size();

How to Switch Selenium Webdriver to Elements over iFrame?

  • Switch To iFrame By Index: Switching to iframe using the index is probably used when there are multiple iframes present on a single web page. Index of iframe starts with 0 and the index gets increasing with the number of iframes embedded. If there are 2 iframes present on a web page, you can use the below code snippet to switch to iframes in Selenium :
  • Switch To iFrame By Name or ID: Name and ID attribute is the most common way of switching to iframe using Selenium. You can easily fetch either the name or ID of the iframe from the browser dev tools.
  • Switch To iFrame By Web Element: Another way of switching to iframe using Selenium is to use the Web Element in the switchTo() command. Here the idea is to get the iframe element from browser dev tools and pass it to the switch method. To locate targeted element over iframe using web element, the below code snippet can be used :
WebElement iframeElement = driver.findElement(By.id("webElementID"));    

How to Switch the Selenium Webdriver Back to the Main Frame?

  1. parentFrame()
  2. defaultContent()

Switching over the iFrame when iFrame ID, Name, and Web Element doesn’t work or isn’t present

public class SeleniumIframe {
public static void main(String[] args) {

WebDriver driver = new ChromeDriver();
int iFrameSize = driver.findElements(By.tagName("iframe")).size(); for(int i=0; i<=iFrameSize; i++){
int elementSize = driver.findElements(By.xpath("html/body/a/advertVideo")).size();

Code Walkthrough :

Handling Nested iFrames in Selenium Test Automation

<div class="iframe">
<div style="overclow:auto;">
<div id="iframewrapper" class="iframewrapper">
<iframe id="iframeResult" frameborder="0">
<iframe width="200" height="200" src="demo_iframe.htm">
  • Firstly, we need to switch to the outer frame, either by name, ID, or index
  • After switching to the outer iframe, we can fetch the count of inner iframes in selenium
  • We can then switch to the inner frame with any of the available types i.e ID, name, or index
  • Lastly, we can interact with the targeted element.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


pCloudy is the most powerful cloud-based App Testing Platform. Brand Marketing @ pCloudy (www.pcloudy.com)