Basic Selenium

Handle frames in selenium webdriver using different approach

In some application for better visibility developer use frame concept in web pages. In this article, we will mainly deal with handle frames in selenium webdriver.

In this case, if your element exists in frames then we have to switch to frame first then we have to perform our operation.

 

handle frames in selenium

In Selenium we can use Switch to method to handle multiple windows, javascript alert, and frames as well.

 

Switch to frame in selenium webdriver

In Selenium we can switch to frames using switchTo () method then perform the action on that element

Syntax-

driver.switchTo().frames();

 

Note- You can give frame name or id or index or WebElement .

 

I created a video on frames which covers the same using 3 methods.

 

Programs to handle frames in selenium

Syntax 1-

In this scenario, if you know the total number of frames in the web page then using the index, you can easily switch.

The index generally starts with zero so if you have only one frame then the index will be zero. If you don’t know the total number of frames in the page then you can use findElementBytagname method.

 

  try {

 driver.switchTo().frame(indexnumber);

      }
catch (NoSuchFrameException e)
     {            

 System.out.println(e.getMessage());     

      }

 

We have enclosed our code with try and catch if now frame will not available this throw exception NoSuchFrameException

 

Syntax 2-

In this scenario, if you know the name  of frames in web page then using name also, you can easily switch

 

try {
driver.switchTo().frame(“framename”);
      } 
 catch (NoSuchFrameException e)
    {            
    System.out.println(e.getMessage());     
    }

 

Check below screenshot that how we can identify that whether element is inside frame or not

 

Syntax 3-

In this scenario

 

 try {
 
WebElement button=driver.findElement(By.xpath(""));  

driver.switchTo().frame(button);

}
catch (NoSuchFrameException e)
     {          
System.out.println(e.getMessage());     

     }

 

Until you are in frames you can not perform any operation so once we are don with frame then switchTo parent window

Syntax-

    driver.switchTo().defaultContent();

 

 

 

 

 

 

 

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.