Java Selenide 关闭所有打开的窗口,包括原始窗口
要关闭所有打开的窗口,包括原始窗口,您可以使用以下代码:
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Selectors.byAttribute;
import static com.codeborne.selenide.Selectors.byText;
public class CloseAllWindowsExample {
public static void main(String[] args) {
// 设置Selenide的默认浏览器为Chrome
Configuration.browser = 'chrome';
// 打开初始窗口
Selenide.open('https://www.example.com');
// 获取初始窗口的句柄
String originalWindowHandle = Selenide.window().getId();
// 打开新的窗口
Selenide.executeJavaScript('window.open('https://www.google.com', '_blank');');
// 等待新窗口打开
Selenide.$$x('//body').findBy(Condition.attribute('target', '_blank'))
.shouldNotBe(Condition.visible);
// 关闭所有窗口,包括初始窗口
for (String windowHandle : Selenide.windowHandles()) {
Selenide.switchTo().window(windowHandle);
Selenide.closeWindow();
}
// 切换回初始窗口
Selenide.switchTo().window(originalWindowHandle);
// 验证是否成功关闭所有窗口
Selenide.$(byText('Example Domain')).shouldBe(Condition.visible);
}
}
这段代码使用了 Selenide 框架来进行浏览器自动化。首先,我们设置了 Selenide 的默认浏览器为 Chrome,并打开了一个初始窗口。然后,我们获取了初始窗口的句柄,打开了一个新的窗口,并等待新窗口打开。接下来,我们使用 Selenide.windowHandles() 来获取所有窗口的句柄,并使用 Selenide.switchTo().window() 方法切换到每个窗口,并使用 Selenide.closeWindow() 方法关闭窗口。最后,我们切换回初始窗口,验证是否成功关闭了所有窗口。
原文地址: https://www.cveoy.top/t/topic/qww6 著作权归作者所有。请勿转载和采集!