If you encounter a new window after clicking a button or link, you will need to use the window switch method.
In this case, the first to open the Baidu search interface, and then use JS to open a Baidu press, and then through the Selenium provides a window switching method to switch windows
Packagecom.test.windows;ImportJava.util.Iterator;ImportJava.util.Set;Importorg.openqa.selenium.By;ImportOrg.openqa.selenium.JavascriptExecutor;ImportOrg.openqa.selenium.WebDriver;ImportOrg.openqa.selenium.firefox.FirefoxDriver; Public classWindowsswitch { Public Static voidMain (string[] args) {Webdriver driver=NewFirefoxdriver (); Driver.get ("Http://www.baidu.com"); Driver.manage (). window (). Maximize (); String Searchhandle=Driver.getwindowhandle (); System.out.println ("Baidu Search handle:" +searchhandle); //get the link to Baidu News, then use JS to open a new windowWaitTime (3000); String href= Driver.findelement (By.cssselector ("[Name=tj_trnews]")). getattribute ("href"); System.out.println ("The link of news is:" +href); Javascriptexecutor Executor=(javascriptexecutor) driver; Executor.executescript ("window.open ('" + href + "')"); WaitTime (3000); Set<String> handles =Driver.getwindowhandles (); Iterator Iterator=Handles.iterator (); Iterator Iterator2=Handles.iterator (); //Enter the Baidu News window and get the title verificationWaitTime (3000); while(Iterator.hasnext ()) {String h=(String) iterator.next (); if(H! =searchhandle) {Driver.switchto (). Window (h); if(Driver.gettitle (). Contains ("Baidu News")) {System.out.println ("Switch to News page successfully"); Break; } Else { Continue; } } } //back to Baidu homepageWaitTime (3000); /** You can switch directly using Searchhandle, or you can use the Driver.switchto (). window (Searchhandle); * IF (Driver.gettitle (). Contains ("Baidu")) {* SYSTEM.OUT.PRINTLN ("Switch to search page successfully"); * Driver.findelement (By.cssselector ("#kw")). SendKeys (* "switch successfully"); } */ while(Iterator2.hasnext ()) {String h=(String) iterator2.next (); if(Searchhandle.equals (h)) {Driver.switchto (). Window (h); if(Driver.gettitle (). Contains ("Baidu a Bit")) {System.out.println ("Switch to search page successfully"); Driver.findelement (By.cssselector ("#kw")). SendKeys ("switch successfully")); Break; } Else { Continue; }}} waitTime (3000); Driver.quit (); } Static Public voidWaitTime (intTime ) { Try{thread.sleep (time); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Operation Result:
Baidu Search handle: {57536d1e-6817-4127-83d6-6eb138f28e51}
The link of news is:http://news.baidu.com/
Switch to News page successfully
Switch to search page successfully
Selenium Test (Java)--Multi-window switch (13)