selenium web 驱动程序如何知道新窗口何时打开然后恢复执行 [英] How can selenium web driver get to know when the new window has opened and then resume its execution

查看:17
本文介绍了selenium web 驱动程序如何知道新窗口何时打开然后恢复执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 selenium web 驱动程序自动化 web 应用程序时遇到问题.

I am facing an issue in automating a web application using selenium web driver.

该网页有一个按钮,单击该按钮会打开一个新窗口.当我使用以下代码时,它会抛出 OpenQA.Selenium.NoSuchWindowException: No window found

The webpage has a button which when clicked opens a new window. When I use the following code, it throws OpenQA.Selenium.NoSuchWindowException: No window found

WebDriver.FindElement(By.Id("id of the button that opens new window")).Click();
//Switch to new window
_WebDriver.SwitchTo().Window("new window name");
//Click on button present on the newly opened window
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click();

为了解决上述问题,我在按钮单击和 SwitchTo 语句之间添加了 Thread.Sleep(50000);.

To solve the above issue I add Thread.Sleep(50000); between the button click and SwitchTo statements.

WebDriver.FindElement(By.Id("id of the button that opens new window")).Click();
Thread.Sleep(50000); //wait
//Switch to new window
_WebDriver.SwitchTo().Window("new window name");
//Click on button present on the newly opened window
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click();

它解决了这个问题,但我不想使用 Thread.Sleep(50000); 语句,因为如果窗口需要更多时间才能打开,代码可能会失败,如果窗口快速打开,那么它使测试不必要地变慢.

It solved the issue, but I do not want to use the Thread.Sleep(50000); statement because if the window takes more time to open, code can fail and if window opens quickly then it makes the test slow unnecessarily.

有什么方法可以知道窗口何时打开,然后测试可以恢复执行?

Is there any way to know when the window has opened and then the test can resume its execution?

推荐答案

您需要将控件切换到弹出窗口,然后才能在其中进行任何操作.通过使用它,您可以解决您的问题.

You need to switch the control to pop-up window before doing any operations in it. By using this you can solve your problem.

在打开弹窗前获取主窗口的句柄并保存.

Before opening the popup window get the handle of main window and save it.

String mwh=driver.getWindowHandle();

现在尝试通过执行一些操作来打开弹出窗口:

Now try to open the popup window by performing some action:

driver.findElement(By.xpath("")).click();

Set s=driver.getWindowHandles(); //this method will gives you the handles of all opened windows

Iterator ite=s.iterator();

while(ite.hasNext())
{
    String popupHandle=ite.next().toString();
    if(!popupHandle.contains(mwh))
    {
        driver.switchTo().window(popupHandle);
        /**/here you can perform operation in pop-up window**
        //After finished your operation in pop-up just select the main window again
        driver.switchTo().window(mwh);
    }
}

这篇关于selenium web 驱动程序如何知道新窗口何时打开然后恢复执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆