Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

testing - How to switch between two windows in browser using Selenium java

I'm working with Selenium Automation. In this, When i click a link in a current window, a new window opens. I just want to switch the control to the new window. But i can't do this.Actually the new window is an auto-generated one. That is, link will be generated dynamically. Help me friends...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To switch between windows we have method.

driver.switchTo().window("window name") 

To get the different windows handle, we have method.

driver.getWindowHandles()

Example:

    File file = new File("G:\Selenium\All_Jars\chromedriver.exe");
    System.setProperty("webdriver.chrome.driver",file.getAbsolutePath() );
    driver = new ChromeDriver();

    //Maximize the window
    driver.manage().window().maximize();

    driver.get("http://www.rediff.com/");

    //Get all window handles
    Set<String> allHandles = driver.getWindowHandles();

    //count the handles Here count is=2
    System.out.println("Count of windows:"+allHandles.size());      

    //Get current handle or default handle
    String currentWindowHandle = allHandles.iterator().next();
    System.out.println("currentWindow Handle"+currentWindowHandle);

    //Remove first/default Handle
    allHandles.remove(allHandles.iterator().next());

    //get the last Window Handle
    String lastHandle = allHandles.iterator().next();
    System.out.println("last window handle"+lastHandle);

    //switch to second/last window, because we know there are only two windows 1-parent window 2-other window(ad window)
driver.switchTo().window(lastHandle);
    System.out.println(driver.getTitle());
    driver.findElement(By.tagName("body")).click();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...