How to handle frames in Selenium?


We can handle frames in Selenium with the help of following methods −

  • switchTo().frame( frameNumber)

    This method uses the frame id as the parameter. The index of frame id starts from 0. NoSuchFrameException is thrown if the frame is not found.

  • switchTo().frame( frameName)

    This method uses the frame name as defined by the developer as the parameter. The frame name is considered a String and is enclosed in quotes. NoSuchFrameException is thrown if the frame is not found.

  • switchTo().frame( WebElement)

    This method uses the webelement as the parameter. NoSuchFrameException is thrown if the frame is not found. StaleElementReferenceException if the frame is no longer active.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FrameSet {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "url with frames";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //grabbing the first frame with the help of index
      driver.switchTo().frame(0);
      //grabbing the frame with the help of frame name
      driver.switchTo().frame(“<<name expression>>“);
      //grabbing the frame with the help of frame webelement
      WebElement name = driver.findElement(By.name(“frame-right”));
      driver.switchTo().frame(driver.findElement(By.name(“<<name expression”)));
      driver.quit();
   }
}

Updated on: 10-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements