selenium web驱动程序如何知道新窗口何时打开然后恢复执行

Ozo*_*one 27 testing selenium window webdriver

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

该网页有一个按钮,单击该按钮可打开一个新窗口.当我使用以下代码时,它会抛出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();
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)

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

有没有办法知道窗口何时打开然后测试可以恢复执行?

San*_*rma 29

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

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

String mwh=driver.getWindowHandle();

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 可能会出现新选项卡已打开但句柄尚未添加到驱动器实例的情况。我的解决方案是在单击获取当前句柄计数之前,然后在 while 循环中检查计数是否发生变化。然后切换到新打开的选项卡,就像这样 `driver.switchTo().window(handles[handles.count() - 1]);` 其中 `handles` 在每次迭代时更新。 (2认同)

jfs*_*jfs 11

您可以等到操作成功,例如,在Python中:

from selenium.common.exceptions    import NoSuchWindowException
from selenium.webdriver.support.ui import WebDriverWait

def found_window(name):
    def predicate(driver):
        try: driver.switch_to_window(name)
        except NoSuchWindowException:
             return False
        else:
             return True # found window
    return predicate

driver.find_element_by_id("id of the button that opens new window").click()        
WebDriverWait(driver, timeout=50).until(found_window("new window name"))
WebDriverWait(driver, timeout=10).until( # wait until the button is available
    lambda x: x.find_element_by_id("id of button present on newly opened window"))\
    .click()
Run Code Online (Sandbox Code Playgroud)