Friday 12 July 2013

Working with frames/iframes in Selenium/WebDriver


Hey Guys,

It has been long time, anything posted in the blog from my side. Busy in trying a new tool WatiN. But this post is related to Selenium and WebDriver. How Selenium2 or Selenium -WebDriver handles frames/iframes. In a very simple word, Frames or IFrames can be treated as web page inside a web page. And no wonder, Selenium also treats them in same line. That means, you have to switch to a frame, to find elements present inside that frame. And you need to come out of the frame when you want to find elements outside of the frame.

1st thing to remember is frame/Iframes are nothing  but Web Elements in side a web page. So you can use findElement() method to find out the frame/Iframe. But there is another simple way, where you only provide the name of the frame and Selenium and Web Driver automatically switch the control to that frame.

Consider the below HTML portion, where two frames are present. To find out an element inside those frames, you need to switch the control to that frame.
######################################################
<frame name="Frame1" id="Frame1">
        -----------
        -----------
        -----------
 </frame>

 <frame name="Frame2" id="Fram2">
        ----------
        -----------
        -----------
  </frame>
######################################################


Lets find out frame1 using find element technique:
WebElement frame = driver.findElement(By.Name("Frame1"));
   or 
WebElement frame = driver.findElement(By.Id("Frame1"));

Now you can use frame object to switch the control.
driver.switchto.frame(frame);

In the method above, you need get the object web element and then use it in switchto method.

But you can directly call the switchto  method on frame name like:
driver.switchto.frame("Frame1");

You can also switch to frame by using index of the frame.
In the above example, to switch to "Frame1" using index, the code will be like :
driver.switchto.frame(0);

And the last thing is once you switch to a frame, then you must go out of the frame to find elements outside of the frame boundry.
driver.switchto.defaultcontent();

Please feel free to leave a comment about this post. I would like to hear from you guys if you have any specific issue/doubts related to handling frames in selenium then I would try to clear.

Thanks!!

1 comment:

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...