Handle Nested Frames in Selenium

Profile picture for user arilio666

In Selenium, you can handle nested frames by using the switchTo.frame() method. To switch to a frame within a frame, you need to switch to the outer frame first and then switch to the inner frame.

For example, to switch to an inner frame within an outer frame, you can use the following code:

driver.switchTo.frame("outerFrameId")
driver.switchTo.frame("innerFrameId")
  • Once you are done interacting with the inner frame, you can switch back to the outer frame using the switchTo.parentFrame() method, switch back to the main content using the switchTo.defaultContent() method.
driver.switchTo.parentFrame()
driver.switchTo.defaultContent()
  • You can also switch back to a specific frame by passing the frame's index as an argument to the switchTo.frame() method.
driver.switchTo.frame(1)
  • Today let us take this site and perform the getText() of the frame with the right text.
  • We should switch to the frame-top and then the three frames inside.
  • Using the frame's name, we can do this easily in Selenium.

        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://the-internet.herokuapp.com/nested_frames");
        driver.manage().window().maximize();
        driver.switchTo().frame("frame-top");
        driver.switchTo().frame("frame-right");
        WebElement rightFrame = driver.findElement(By.tagName("body"));
        String rightFrameText = rightFrame.getText();
        System.out.println(rightFrameText);
        
        driver.quit();
  • So here we first navigated to the frame-top, which is the outer shell frame.
  • Then we navigated to the required frame with the 'right' text.
  • We can see the frame has been accessed, and then the text has been retrieved.