Quit method: Exit the related driver and close all windows
Close method: Closes the current window
PackageCom.test.closewindow;ImportJava.util.Iterator;ImportJava.util.Set;Importorg.openqa.selenium.By;ImportOrg.openqa.selenium.JavascriptExecutor;ImportOrg.openqa.selenium.WebDriver;ImportOrg.openqa.selenium.firefox.FirefoxDriver; Public classWindowsclose { Public Static voidMain (string[] args) {Webdriver driver=NewFirefoxdriver (); Driver.get ("Http://www.baidu.com"); Driver.manage (). window (). Maximize (); String Searchhandle=Driver.getwindowhandle (); String Newshandle=NULL; 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"); Newshandle=Driver.getwindowhandle (); 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")); Driver.close ();//only close Baidu homepageSystem.out.println ("Close search page successfully"); Driver.switchto (). window (newshandle);//Switch to Baidu NewsSystem.out.println ("The current title is:" + driver.gettitle ());//Get titleWaitTime (3000); Break; } Else { Continue; }}} waitTime (3000); Driver.quit (); } Static Public voidWaitTime (intTime ) { Try{thread.sleep (time); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Execution Result:
Baidu Search handle: {75749f9a-f6b7-4fe6-80ae-dd9e053dd577}
The link of news is:http://news.baidu.com/
Switch to News page successfully
Switch to search page successfully
Close Search Page successfully
The current title is: Baidu News search-the world's largest Chinese news platform
Selenium Test (Java)-close window (20)