Realization of selenium multi window switching (Windows)

Time:2020-8-1

In the web application, it is often met that clicking a link will pop up a new window or related web application. In this way, to operate the elements in the new window, the host needs to switch to the new window for operation.. Webdriver provides switchto(). Window() method to switch between different windows.

The following code is to Sina. Com as an example. Switch to the specified window by getting the handle and close the window. Of course, if you switch to the specified window, you can also operate the elements by element positioning and other methods.

Getwindowhandle(): gets the current window handle.

Getwindowhandles(): handles of all windows returned to the current session.

Switchto(). Window(): used to switch to the corresponding window. Similar to switchto(). Frame() in the previous section, the former is used for switching between different windows, and the latter is used for switching between different forms.  

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

System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
ChromeOptions Options = new ChromeOptions();
Options.addArguments("user-data-dir=C:\Users\happy\AppData\Local\Google\Chrome\User Data");
WebDriver driver = new ChromeDriver(Options);
driver.manage().window().maximize();
//Maximize window
driver.get("http://www.sina.com.cn/");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
//Set element waiting time, implicit wait
String sreachHand = driver.getWindowHandle();
//Gets the handle to the current window
driver.findElement ( By.linkText (P.E.)). Click();
//Open the sports link on Sina's official website
driver.findElement ( By.linkText (entertainment). Click();
//Open the entertainment link on Sina's official website
java.util.Set<String> Handles = driver.getWindowHandles();
System.out.println ( Handles.size () + "set length");
//Gets handles to all windows and places them in the set collection.
//The following judgment is Sina home page, if so, close Sina home page.
for (String i : Handles) {
if (i.equals(sreachHand)) {
driver.switchTo().window(i);
Thread.sleep(5000);
driver.close();

}
}

}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.