How to switch to frames in Selenium?

Software TestingAutomation TestingSelenium Web Driver

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();
   }
}
raja
Published on 10-Jun-2020 18:30:32
Advertisements