Selenium挂在循环中

时间:2014-03-09 17:56:07

标签: javascript selenium xpath

由于我在主页上有许多链接,每个链接都需要不同的应用程序。单击每个链接后将打开新选项卡/窗口,在新选项卡中我需要检查特定元素的存在(使用从excel传递给所有应用程序的元素的xpath)。检查元素的存在后,我需要关闭子窗口并切换回父窗口,并按照相同的过程继续链接(1000+)。我的脚本只有在非应用程序/窗口挂起时才能正常工作,如果任何应用程序未加载或挂起,则脚本无法关闭子窗口并切换回父级继续使用其他链接进行测试。

  • 页面加载的工作原理是什么?
  • 我想在等待几秒后关闭子窗口,即使它加载页面并切换回父窗口

1 个答案:

答案 0 :(得分:0)

我编写了一个实用程序类,它处理窗口并跟踪所有打开的窗口句柄。使用它,该项目最多运行4个打开的浏览器弹出窗口,然后按顺序关闭它们。

请参阅the project here

这可能会有很大改进,但这是一个来自该类的示例方法:

/**
 * Loops to determine if WebDriver.getWindowHandles() returns any
 *  additional windows that the allHandles cache does not currently
 *  contain. If new window is found that is not in the cache, switch 
 *  to that latest window and update allHandles cache.
 */
public static String handleNewWindow() {
    String newHandle = "";
    printHandles();
    Set<String> updatedHandles = driver.getWindowHandles();
    if ( updatedHandles.size() < handleCache.size() ) {
        mainHandle = "";
        LOGGER.info("Illegal state: actually, I saw a window close.");
        throw new IllegalStateException("This method handleNewWindow is not appropriate\n" +
                "in this case.  You are probably looking for the\n"+
                "use of the updateHandleCache method.");
    } else if ( updatedHandles.size() == handleCache.size() ) {
        LOGGER.info("handleNewWindow() will do nothing because there are no new window handles.");
    } else {
        if ( !updatedHandles.isEmpty() ) {
            for ( String windowId : updatedHandles ) {
                if ( !windowId.equals( mainHandle ) ) { // for all windows except main window
                    if ( !handleCache.contains( windowId) ) { // for child windows not in allHandles cache
                        newHandle = windowId; // set value of newly found window handle                     
                        LOGGER.info("-- Open window handle: " + newHandle + " (new window)" );
                    }
                }
            }
            if ( !newHandle.equals("") ) { // outside loop so it catches latest window handle if there are multiple
                LOGGER.info("Switch to new window.");
                driver.switchTo().window( newHandle ); // switch to new window handle
            }
        } else {
            mainHandle = "";
            throw new IllegalStateException("No browser window handles are open.");
        }
    }
    handleCache = updatedHandles; // updates remembered set of open windows
    return newHandle;
}