selenium 中如何处理弹出窗口

 

阅读目录

 

原理

在代码里, 通过         Set<String> allWindowsId = driver.getWindowHandles();

来获取到所有弹出浏览器的句柄,   然后遍历,  使用swithcto.window(newwindow_handle)方法。 就可以定位到新的窗口

 

测试页面的HTML

<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>

 

Java 代码

    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());
    }

 

 

 

 

posted on 2016-03-12 19:51  小坦克  阅读(16394)  评论(0编辑  收藏  举报