Selenium and iframe in html.

SeleniumAutomation TestingTesting ToolsHTML

We can work with iframe in Selenium webdriver. A frame is defined with <iframe>, <frameset> or <frame> tag in html code. A frame is used to embed an HTML document within another HTML document.

Selenium by default has access to the parent browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. There are more than one methods to shift to frames −

  • switchTo().frame(id) - The id or name of frame is passed as an argument.

    Syntax − driver.switchTo().frame("id"), switching to the frame with id.

  • switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.

    Syntax − driver.switchTo().frame(0), switching to the first frame in the page.

  • switchTo().frame(webelement n) - The webelement of frame is passed as an argument.

    Syntax − driver.switchTo().frame(l), switching to the frame with webelement l.

  • switchTo().defaultContent() – Switching focus from frame to the main page.

    Syntax − driver.switchTo().defaultContent()


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class iFrameMethods{
   public static void main(String[] args) {
      System.setProperty("", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      // identify element and click
      // switching to frame with frame name
      WebElement m = driver.findElement(By.cssSelector("body"));
      System.out.println("Frame text: " +m.getText());


Published on 26-Oct-2020 11:27:44