Handling Multiple Frames in Selenium

Profile picture for user arilio666

In Selenium, a web page can contain multiple frames, essentially independent HTML documents nested within the main document. When working with multiple frames, there are a few things to keep in mind:

Identify the frame: To interact with elements inside a frame, you first need to switch the focus to the frame. You can do this by using the switchTo().frame() method and passing in either the frame element or its name or ID.

Switch back to the default content: Once you interact with the elements inside a frame, you must switch back to the main document by calling switchTo().defaultContent().

Nesting frames: If you have frames nested inside other frames, you need to switch to the parent frame before switching to the child frame. You can do this by calling switchTo().parentFrame().

Consider this site. For example, this has three frames.

These are the three frames within this page, and we will traverse between each frame and perform operations.

package week4.day2;

import org.openqa. Selenium.By;
import org.openqa. Selenium.WebElement;
import org.openqa. Selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Frame {

    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://www.maths.surrey.ac.uk/explore/nigelspages/frame2.htm");
        driver.manage().window().maximize();

        WebElement frameOne = driver.findElement(By.xpath("//frame[@src='htmlf.htm']"));

        driver.switchTo().frame(frameOne);
        driver.findElement(By.xpath("//a[normalize-space()='Javascript Scientific Calculator']")).click();

        driver.switchTo().defaultContent();

        WebElement frameTwo = driver.findElement(By.xpath("//frame[@src='message.htm']"));

        driver.switchTo().frame(frameTwo);

        driver.findElement(By.xpath("//input[@name='name']")).sendKeys("Naruto");

        driver.switchTo().defaultContent();

        WebElement frameThree = driver.findElement(By.xpath("//frame[@src='tags.htm']"));

        driver.switchTo().frame(frameThree);

        String text = driver.findElement(By.xpath("//font[contains(text(),'Brief')]")).getText();
        System.out.println(text);
        // driver.quit();

    }

}
  • We switched to the first frame and clicked on the HTML link.
  • In the second frame, we sent keys.
  • In the third frame, we got the text of the element.
  • Each time we switch, we use the switch to the default content.
  • Then switch to the respective frames.
  • This is how we can handle multiple frames in Selenium.