0

我对 Selenium/webdriver 相当陌生。我编写了一个运行多次迭代的测试用例。在第一个上会出现一个弹出窗口。但是,在后续迭代中,弹出窗口不存在。如何重新编写它,以便在继续执行下面的代码之前检查弹出窗口?谢谢

    String Parentwindow = oWD.getWindowHandle();

    //Click Search button  -- This will cause the pop-up
    oWD.findElement(By.id("uw_fc_sub_anc")).click();
    Thread.sleep(1000);


    for(String ChildWindow : oWD.getWindowHandles())
    {
        oWD.switchTo().window(ChildWindow);
    }
    oWD.close();
    oWD.switchTo().window(Parentwindow);
4

3 回答 3

1

I would probably factor this out into a helper method that did something like the following:

public String clickAndFindPopup(WebDriver driver, By locator) {
    // Get the original list of handles to evaluate if a popup
    // needs to be handled.
    List<String> existingHandles = driver.getWindowHandles();

    //Click Search button  -- This will cause the pop-up
    driver.findElement(locator).click();
    Thread.sleep(1000);

    List<String> windowHandles = driver.getWindowHandles();
    windowHandles.removeAll(existingHandles);

    if (windowHandles.size() > 0) {
        return windowHandles.get(0);
    }

    return "";
}

Then you could do something like this:

String popupHandle = clickAndFindPopup(driver, By.id("uw_fc_sub_anc"));
if (!popupHandle.equals("")) {
    String currentHandle = driver.getWindowHandle();
    driver.switchTo().window(popupHandle);
    driver.close();
    driver.switchTo().window(currentHandle);
}

The drawback here is that, if you truly only expect the popup on the first iteration, you might dismiss a popup window that you shouldn't be, because you're blindly closing the popup whenever you find one. A much better approach would be to know what state you expect the browser to be in when you're automating it, and asserting on it.

于 2013-05-06T16:34:44.630 回答
0

尝试创建一个布尔函数并使用 try catch 来处理弹出窗口

于 2013-05-07T04:20:20.960 回答
0

我使用 try catch 来处理“可能的通知”。我捕获了由不存在的元素生成的两个可能的异常。这是 C# 顺便说一句:

            public void ClosePossibleRandomNotification()
        {
            bool exists=false;
            try
            {
                Browser.Driver.FindElement(By.XPath("..."));
                exists = true;
            }

            catch (ElementNotVisibleException)
            {
                exists = false;
            }

            catch (NoSuchElementException)
            {
                exists = false;
            }

            if (exists){
                try
                {
                    //close the pop up
                }
                catch (ElementNotVisibleException)
                {
                    exists = false;
                }

            }
        }
于 2013-05-06T12:02:27.340 回答