How to switch to frames in Selenium?


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

  • switchTo()defaultContent()

    This method is for switching to and fro in between frames and parent frames. The focus is shifted to the main page.

  • switchTo().parentFrame()

    This method is used to switch the control to the parent frame of the current frame.

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 FrameDefault {
   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);
      System.out.println("Getting the page source " + driver.getPageSource());
      // switching back to the parent web page
      driver.switchTo().defaultContent();
      driver.quit();
   }
}

Updated on: 10-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements