随笔 - 137  文章 - 2  评论 - 2715  阅读 - 540万 

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   小坦克  阅读(16449)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示