SUBSCRIBE HERE TO GET POST UPDATES VIA EMAIL :

Delivered by FeedBurner

switchTo() iFrames using index in Selenium WebDriver

We can use switchTo() method when you want to switch between multiple browser windows or multiple frames on page. Earlier we had seen how to switch between two windows using getWindowHandles() and switchTo() methods. Here we will see how to switch between iFrames on page using switchTo() method by index of iFrame.

When you have multiple frames on page, You can use index of frame to switch between iFrames. Let's see how can we switch between iFrames using index.

How to Switch between iFrames using index?
package TestPack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class switchtoiFrameindex {

 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  driver.manage().window().maximize();
  
  driver.get("http://only-testing-blog.blogspot.com/2015/01/iframe1.html");
  
  //Get how many number of iFrames on page. We can identify iFrame by tagName iframe.
  //We have total 2 iframes on page.
  int size = driver.findElements(By.tagName("iframe")).size();
  System.out.println(size);
  
  //Switch to iFrame having 0 index and perform click action on checkbox.
  driver.switchTo().frame(0);
  driver.findElement(By.xpath("//td[contains(text(),'Tiger')]/preceding-sibling::td/input[@type='checkbox']")).click();
  
  //Switch back to main page content and input text in Town textbox 
  driver.switchTo().defaultContent();
  driver.findElement(By.xpath("//input[@name='Town']")).sendKeys("My Town");
  
  //Switch to iFrame having 1 index and perform click action on checkbox.
  driver.switchTo().frame(1);
  driver.findElement(By.xpath("//input[@value='Boat']")).click();
 }

}

In above example test page, We have two iframes. driver.switchTo().frame(0); will select iframe one and then it will select checkbox with "Tiger" label inside iframe one.

Then driver.switchTo().defaultContent(); will switch back to main page content and next will type some text in Town textbox.

Then driver.switchTo().frame(1); will select iframe two and select the checkbox having label "I have a boat" inside iframe two.

This is the example of how to switch between iFrames using index of iframes.

No comments:

Post a comment