如何使用selenium/java切换到新的弹出窗口。

huangapple go评论69阅读模式
英文:

How to switch to a new pop-up window using selenium/java

问题

我需要自动化执行以下测试:
在网页登录后,会弹出一个新的应用程序弹窗,所有步骤都应在这个新弹窗中完成。

问题:
如何编写代码以从当前登录窗口切换到新的弹出窗口?

谢谢!

英文:

I need to automate the following test:
after the login on the web page a new pop-up window (with app) opens and all steps should be done in this new window.

Question:
how to code to switch from the current login window to the new pop-up window?

Thank you!

答案1

得分: 1

如果您想处理子窗口,您需要在Selenium中使用句柄。请参考以下代码:

String parentWindowHandle = driver.getWindowHandle(); // 获取当前窗口句柄

// 在父窗口上执行操作
// 在父窗口上执行click()操作,打开一个新窗口

for (String winHandle : driver.getWindowHandles()) {
    if (!winHandle.equals(parentWindowHandle)) {
        driver.switchTo().window(winHandle); // 在这里切换到子窗口,以便在子窗口上执行操作
        System.out.println("新窗口的标题: " + driver.getTitle());
        // 在新窗口上执行某些操作的代码
        System.out.println("关闭新窗口...");
        driver.close();
    }
}

driver.switchTo().window(parentWindowHandle);
System.out.println("父窗口的URL: " + driver.getCurrentUrl());
英文:

If you want to handle child window then you have to use handles in seleneium, Kindly refer below code:

String parentWindowHandle = driver.getWindowHandle(); // get the current window handle

//Perform action on your parent window 
//Perform clcik() action on your parent window that opens a new window    

for (String winHandle : driver.getWindowHandles()) {
 
         if(!winHandle.equals(parentWindowHandle))
         {
            driver.switchTo().window(winHandle); // Here yor switching control to child window so that you can perform action on child window
            System.out.println("Title of the new window: " +
            driver.getTitle());
            //code to do something on new window
        	System.out.println("Closing the new window...");
            driver.close();
         }

   }   

driver.switchTo().window(parentWindowHandle);
System.out.println("Parent window URL: " + driver.getCurrentUrl());

huangapple
  • 本文由 发表于 2020年4月9日 23:43:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61124939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定