Selenium switchTo() iFrames using index

We can use switchTo() method in selenium 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. You need switch to iframe in selenium when you have take action inside iframe on page. There are many different ways to handle iframe in selenium and you can use selenium switchto method to work with iframe. Selenium switch to iframe using index will locate inframe using it's index. 

Here we will see how to switch between iFrames in selenium using switchTo() method by index of iFrame. Switch to iframe in selenium using index will locate iframe by index. 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.

Selenium Switch to iFrame using index Example

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);
  
  //Selenium 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 selenium switchto that iframe 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 in selenium using index of iframes.

No comments:

Post a Comment