Handling iframes in selenium

There are situations where web controls/elements reside inside an iframe.

iframe can be represented in html as tag name="iframe".


Elements inside an iframe can not be accessed as normal selenium statement - driver.findelement(By...)

need to use, driver.switchTo().frame(...);

In selenium, how we can identify if web element[s] is/are inside an <iframe ...=""> </iframe> ???
Right click on an web element, check if the context menu has any one of the following options -


If you get the options like above screenshot, then there are ways we can identify the web elements-

Individual iFrames


driver.switchTo().frame(int x); //by index, if  one or more frames present
driver.switchTo().frame(String frameName); //frame by name
driver.switchTo().frame(WebElement element); //frame by locator

Nested iFrames


If there are nested iframes, then we can use
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);


Out of iFrames


Once complete the action on the iframe elements, if we want to come out of the frame, then do
driver.switchTo().defaultContent(); //to come out of a frame for normal run

That's it about the brief, now let's see the code implementation
                           -------------------------------------------------------
We will try to access the "Category1" link (inside an iframe) on website www.qavalidation.com demo as a normal webelement and see what happens

public class Form1 {
public static void main(String[] args) {
   WebDriver driver = new FirefoxDriver();
   driver.manage().window().maximize();
   driver.manage().deleteAllCookies();
   driver.get("http://www.qavalidation.com/p/demo_8.html");
   driver.findElement(By.linkText("Category1")).click();
  }
}

OutPut

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Category1"}
Command duration or timeout: 468 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.45.0', revision: '32a636c', time: '2015-03-05 22:01:35'

Now let's try to access the iframe elements by using driver.switchTo().Frame...

public class Form1 {
public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().deleteAllCookies();
    driver.get("http://www.qavalidation.com/p/demo_8.html");
    //driver.switchTo().frame(0); //frame by index
    driver.switchTo().frame("Framename1"); //frame by name
    //frame identification by any one of the locator
    //driver.switchTo().frame(driver.findElement(By.id("Frame1"))); 
    driver.findElement(By.linkText("Category1")).click(); //inside an iframe
    driver.switchTo().defaultContent();
    driver.findElement(By.linkText("Pavilion")).click();//normal webelement
  }
}

No comments:

Post a Comment