gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:07:29 24 4
gpt4 key购买 nike

我想在selenium中从父窗口切换到子窗口,而不使用增强的for循环,到目前为止,我用来从父窗口切换到子窗口的代码如下,

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

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

最佳答案

您遇到的无法切换的问题可能是由于等待问题。您可能单击了链接以打开新窗口,但 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);
}

关于java - 切换到子窗口 [通过使用 while.HasNext() 函数],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34285116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com