有没有办法查看是否所有的浏览器窗口都关闭了?我看到如果您在 WebDriver 上调用 driver.quit() 或 driver.close(),则 sessionId 变为空。有没有办法检查?
我不想调用已关闭或退出的驱动程序,因为它会引发 WebDriverException。所以我想在继续之前检查浏览器的状态。
刚设置
driver=null;
每次你退出浏览器,然后检查
if (browser!=null){
//Attention: this comand is not supported
//as far as i know ;)
driver.doSomething();
}
或者
try{
}catch (NullPointerException e)
e.printStackTrace();
System.err.print"DAMN";
}
或收到 NullPointerException ;)
public bool InstanceExist
{
get
{
if (Instance != null)
{
try
{
return (Instance.WindowHandles != null); // allways returns true if browser instance exist or thrown error
}
catch (Exception e)
{
return false;
// means that browser was closed by user
}
}
return false; // means that it wasn't created yet or was closed by developer programmally
}
}
你需要检查3种情况:
使用此代码检查所有这些情况。
我认为检测是否所有窗户都关闭的最干净的方法是:
boolean allWindowsClosed = webDriver.getWindowHandles().isEmpty();
getWindowHandles 为所有打开的窗口返回一组窗口句柄 - 请参阅http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.html#getWindowHandles()
实际上在浏览器窗口消失时调用 getWindowHandles 会引发“UnreachableBrowserException”。
您必须将调用放入 try-catch 块并处理该错误。实际上,这是捕获意外浏览器窗口关闭的唯一已知工作方法。我在配置类中有一个静态方法来处理我的驱动程序:我像这样重新启动浏览器:
protected static void loadPages() {
if (driver == null || driver.toString().contains("null")) { //null refers to an missing session id
driver = new FirefoxDriver();
//load all my page objects like
loginpage = new LoginPage(driver);
//....
//....
}
try {
if (driver.getWindowHandles() == null || driver.getWindowHandles().isEmpty()){ //will cause an UnreachableBrowserException if the browser really is not avalable.
try { //you actually dont need this try catch block
driver.quit();
} catch (Exception e) {
System.err.println("Quitting levtover driver did not work.");
}
driver = null; //you have to set the driver to null
loadPages();
}
} catch (UnreachableBrowserException ube) {
driver = null; //like above set to null to make sure no driver left
}
}
现在,您当前的测试将失败,但您将能够继续进行其余测试。
在 C# 中
public void BrowserCheck()
{
try
{
var h = webDriver.WindowHandles;
return; // no problem
}
catch // browser window is closed so re-init it
{
webDriver.Quit();
WebDriverInit(); // your init code
}
}