How to handle frame in Selenium WebDriver using java?

SeleniumAutomation TestingTesting Tools

We can handle frames in Selenium webdriver. A frame is identified with <frame> tag in the html document. A frame is used to insert an HTML document inside another HTML document.

To work with frames, we should first understand switching between frames and identify the frame to which we want to move. There are multiple ways to switch to frames −

  • switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0.

Syntax −

driver.switchTo().frame(1), we shall switch to the frame with index 1.
  • switchTo().frame(name) - The frame id or name is passed as an argument to switch to.

Syntax −

driver.switchTo().frame("fname"), we shall switch to the frame with name fname.
  • switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to.

Syntax −

driver.switchTo().frame(n), we shall switch to the frame with webelement n.
  • switchTo().defaultContent() – To switch back to the main page from the frame.

Syntax −

driver.switchTo().defaultContent()

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Framehandling{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://the-internet.herokuapp.com/frames";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      driver.findElement(By.linkText("Nested Frames")).click();
      // switch to frame with frame name and identify inside element
      driver.switchTo().frame("frame-bottom");
      WebElement l = driver.findElement(By.cssSelector("body"));
      System.out.println("Bottom frame text: " +l.getText());
      // switch to main page
      driver.switchTo().defaultContent();
      driver.quit();
   }
}

Output

raja
Published on 28-Aug-2020 12:42:45
Advertisements