Thursday, July 19, 2012

How to handle/switch windows, Tabbed browser and Pop ups in Selenium 2 Webdriver



Below is java code which explains how window switching/different windows(Tabs or Popups) are handled in Selenium. This example is performed on expedia.com.

Copy paste the below code in eclipse and run.

Choose Easy Way



Note 1 - Selenium opens all the tab windows as POPUPS all the time.
Note 2 - Each window has a unique id which helps in its identification and therefore switching.


import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class HandlingBrowser {


public static void main(String[] args) throws InterruptedException {

WebDriver driver = new FirefoxDriver();

System.out.println("************Open Expedia website************");
driver.get("http://www.expedia.com");

//This will get window ID's
Set<String> windowIds = driver.getWindowHandles();
Iterator<String> iter = windowIds.iterator();
while(iter.hasNext()){
System.out.println("This is First Id - " + iter.next());

}

//Click on Feedback
driver.findElement(By.xpath(".//*[@id='nav-tool-feedback']")).click();

windowIds = driver.getWindowHandles();
iter = windowIds.iterator();
while(iter.hasNext()){
System.out.println("This is Second Id - " + iter.next());
}

windowIds = driver.getWindowHandles();
iter = windowIds.iterator();
String mainWindowId = iter.next();
String tabbedWindowId = iter.next();

driver.close();

System.out.println("************ Windows Switching has been handled successfully************");
//This will switch window control to the other window
driver.switchTo().window(tabbedWindowId);
driver.findElement(By.xpath(".//*[@id='main']/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[1]/input")).click();
driver.findElement(By.xpath(".//*[@id='submitImage']")).click();

windowIds = driver.getWindowHandles();
iter = windowIds.iterator();

driver.close();
System.out.println("************Test successful************");

}

}


No comments:

Post a Comment