Selenium WindowHandles未检测到所有打开的弹出窗口

时间:2016-07-06 10:28:58

标签: c# selenium-webdriver

我正在尝试在两个打开的Popup之间切换。但是driver.WindowHandles只返回1个句柄(ID)。我不知道如何切换到第二个弹出窗口。 命令driver.SwitchTo().ActiveElement不起作用。

ReadOnlyCollection<string> currentHandlesList = driver.WindowHandles;
Console.WriteLine(currentHandlesList.Count);

结果:1​​

为什么会返回1.为什么不返回?

非常感谢。

1 个答案:

答案 0 :(得分:0)

您应该使用以下方法: -

string currentHandle = driver.CurrentWindowHandle;
//Save the currently-focused window handle into a variable so that you can switch back to it later.

ReadOnlyCollection<string> originalHandles = driver.WindowHandles;
//Get the list of currently opened window handles.

// Now work here to open popups

// WebDriverWait.Until<T> waits until the delegate return the popup window handle.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

string popupWindowHandle = wait.Until<string>((d) =>
{
    string foundHandle = null;

    // Subtract out the list of known handles. In the case of a single
    // popup, the newHandles list will only have one value.
    List<string> newHandles = driver.CurrentWindowHandles.Except(originalHandles).ToList();
    if (newHandles.Count > 0)
    {
        foundHandle = newHandles[0];
    }

    return foundHandle;
});

driver.SwitchTo().Window(popupWindowHandle);

// Do whatever you need to on the popup browser, then...
driver.Close();
driver.SwitchToWindow(currentHandle);

通过这种方式你可以使用弹出窗口..希望它能帮到你.. :)