Saturday, May 31, 2014

How to handle multiple windows.

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class MultipleWindows {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://selenium-makeiteasy.blogspot.in/");
       
        WebElement ele = driver.findElement(By.xpath("//a[text()='View my complete profile']"));
        Actions act = new Actions(driver);
        act.moveToElement(ele).contextClick().sendKeys("W").perform(); //this will open the link in new window
       
        Iterator<String> addWindow = driver.getWindowHandles().iterator(); //get the address of all opened windows
        String mainPage = addWindow.next(); //get the address of main page
        String childPage = addWindow.next();//get the address of child page
       
        driver.switchTo().window(childPage); //switch the control to child window
        driver.findElement(By.xpath("//a[text()='Automate the website']")).click(); //this will click in child window's interests- Automate the website link
        Thread.sleep(5000); //simply added wait for 5sec so that one can see the how it works in new window
        driver.close(); //this will close the child window
       
        driver.switchTo().window(mainPage); //switch back to main window
        List<WebElement> pageView = driver.findElements(By.xpath("//span[@id='Stats1_totalCount']/span"));//this will give the all the WebElements of the Total Pageviews numbers
        for(WebElement num: pageView){
            System.out.print(num.getText()); //this will print the number of Total Pageviews
        }
        driver.close(); //this will close main window as well
    }
}

No comments:

Post a Comment