Handle Frames using Selenium WebDriver

Its very easy to deal with frames in selenium WebDriver. Frames or IFrames can be treated as a web page inside a web page or you can also say that frames are just web elements inside a web page but keep in mind one thing that you have to switch the focus to frame in order to interact with the elements inside that frame.
Before switching the control to a frame, first you have to find out where it is located in a webpage, for that you can use findElement() function or if frame has name or id attribute then you can directly use these attributes and web driver will automatically switch the control to that frame.

Lets take an example of below html code that contains two frames:

<body>
   <div id = "autoapp">
     <iframe id = 'f1'>
      -------------- 
      --------------
     </iframe>

     <iframe id = 'f2'>
     --------------
     --------------
     </iframe>
</div>
</body>

1st option : Use frame ID or name

Below command will switch the control to frame whose id is ‘f1’

driver.switchTo().frame("f1");

2nd option : We can also use index . In above example, we have 2 frames, so index of first frame is 0 and for second frame is 1

driver.switchTo().frame(0);

3rd option : We can also use xpath or css selectors for switching control to a frame

xpath of frame1 would be – //div[@id=”autoapp”]/iframe
xpath of frame2 would be – //div[@id=”autoapp”]/iframe[2]

Below commands will switch the control to Frame 1

WebElement frame1 = driver.findElement(By.xpath("//div[@id="autoapp"]/iframe"));
driver.switchTo().frame(frame1 );

CSS of frame1 would be – div.autoapp > iframe
CSS of frame1 would be – div.autoapp iframe:nth-child(2)

Below commands will switch the control to frame 2

WebElement frame2 = driver.findElement(By.cssSelector("div.autoapp iframe:nth-child(2)"));
driver.switchTo().frame(frame1 );

Once you done with operations inside a frame, you have to move out in order to find elements outside the frame. For that you have to switch the focus back to window, otherwise you script will fail.

Command to switch the control back to its default is :-

driver.switchTo().defaultContent();



If you really like the information provided above, please don’t forget to leave the comment. You can also like us on Facebook.

Leave a Reply

Your email address will not be published. Required fields are marked *