大多数人在处理 IE 中的弹出窗口时错过的部分是对元素的单击是异步的。也就是说,如果您.WindowHandles
在单击后立即检查属性,您可能会失去竞争条件,因为您在 IE 有机会创建新窗口之前检查是否存在新窗口,并且驱动程序已经有机会注册它。
这是我用来执行相同操作的 C# 代码:
string foundHandle = null;
string originalWindowHandle = driver.CurrentWindowHandle;
// Get the list of existing window handles.
IList<string> existingHandles = driver.WindowHandles;
IWebElement addtoList = driver.FindElement(By.XPath(_pageName));
addtoList.Click();
// Use a timeout. Alternatively, you could use a WebDriverWait
// for this operation.
DateTime timeout = DateTime.Now.Add(TimeSpan.FromSeconds(5));
while(DateTime.Now < timeout)
{
// This method uses LINQ, so it presupposes you are running on
// .NET 3.5 or above. Alternatively, it's possible to do this
// without LINQ, but the code is more verbose.
IList<string> currentHandles = driver.WindowHandles;
IList<string> differentHandles = currentHandles.Except(existingHandles).ToList();
if (differentHandles.Count > 0)
{
// There will ordinarily only be one handle in this list,
// so it should be safe to return the first one here.
foundHandle = differentHandles[0];
break;
}
// Sleep for a very short period of time to prevent starving the driver thread.
System.Threading.Thread.Sleep(250);
}
if (string.IsNullOrEmpty(foundHandle))
{
throw new Exception("didn't find popup window within timeout");
}
driver.SwitchToWindow(foundHandle);
// Do whatever verification on the popup window you need to, then...
driver.Close();
// And switch back to the original window handle.
driver.SwitchToWindow(originalWindowHandle);
顺便说一句,如果您使用的是 .NET 绑定,则可以访问PopupWindowFinder
WebDriver.Support.dll 程序集中的一个类,它使用与定位弹出窗口非常相似的方法。您可能会发现该类完全符合您的需求,并且无需修改即可使用它。