selenium 中如何處理彈出窗口javascript
在代碼裏, 經過 Set<String> allWindowsId = driver.getWindowHandles();java
來獲取到全部彈出瀏覽器的句柄, 而後遍歷, 使用swithcto.window(newwindow_handle)方法。 就能夠定位到新的窗口web
<html> <head> <title>常見web ui元素操做, 及API使用</title> <script type="text/javascript"> function open_win() { window.open("http://www.cnblogs.com") } </script> </head> <body> <form> <input type=button value="打開窗口" onclick="open_win()"> </form> </div> </body> </html>
public static void testMultipleWindowsTitle(WebDriver driver) throws Exception { String url="E:\\StashFolder\\huoli_28@hotmail.com\\Stash\\Tank-MoneyProject\\Selenium Webdriver\\AllUIElement.html"; driver.get(url); // 獲取當前窗口的句柄 String parentWindowId = driver.getWindowHandle(); System.out.println("driver.getTitle(): " + driver.getTitle()); WebElement button = driver.findElement(By.xpath("//input[@value='打開窗口']")); button.click(); Set<String> allWindowsId = driver.getWindowHandles(); // 獲取全部的打開窗口的句柄 for (String windowId : allWindowsId) { if (driver.switchTo().window(windowId).getTitle().contains("博客園")) { driver.switchTo().window(windowId); break; } } System.out.println("driver.getTitle(): " + driver.getTitle()); // 再次切換回原來的父窗口 driver.switchTo().window(parentWindowId); System.out.println("parentWindowId: " + driver.getTitle()); }