切换到子窗口[通过使用while.HasNext()函数]

时间:2015-12-15 09:13:53

标签: java selenium

我想在不使用增强型for循环的情况下从父窗口切换到selenium中的子窗口,直到现在我用于从父级切换到子级的代码如下所示,

for(String handles : windows1)
{
    w.switchTo().window(handles);
    Thread.sleep(3000);
}

但是当我执行此代码5次时,3次selenium切换到子窗口,但是2次无法切换。有人提出了一个很好的解决方案来切换到子窗口,即使我执行N次也不会失败。

1 个答案:

答案 0 :(得分:0)

您未能切换的问题可能是由于等待问题。您可能已单击链接以打开新窗口,但Selenium未注册新窗口。如果windowHandles包含预期的窗口数,for循环将永远不会迭代。

// Get the current active window (parent window) 
String parentHandle  = driver.getWindowHandle();

// click or do an operation to open a new window
w.findElement(By.id('linkToOpenNewWindow')).click();


// loop max 10 times waiting 5 seconds between each iteration
// until the windowHandles size > 1 
Set<String> windows1 = null;
for (int i=0 ; i<10 ;i++) {
    windows1 = driver.getWindowHandles();
    if (windows1.size() > 1 || windows1 != null) {
        break;
    Thread.sleep(5000);
}

Assert.assertTrue(windows1.size()>1, "There is no child window");

// Remove the parent handle from the list of windowHandles
// This will prevent the unnecessary looping to the active window
windows1.remove(parentHandle);

// iterate through the windowHandles
for(String handles : windows1) {
    w.switchTo().window(handles);
    Thread.sleep(3000);
}