首页 > 解决方案 > 无效参数异常后如何退出 ChromeDriver

问题描述

这是我当前的代码:

options.addArguments("--user-data-dir=Profile");
try {
  driver = new ChromeDriver(options);
}
catch (Exception org.openqa.selenium.InvalidArgumentException) {
  driver.quit
}

InvalidArgumentException 在浏览器窗口已经打开之前不会抛出,如果我尝试在 catch 块中退出它,它显然会打印一个空指针异常,因为驱动程序从未完全初始化。如何处理 InvalidArgumentException,例如正在使用的用户数据目录,同时关闭已经打开的 chromedriver 窗口。

标签: javaseleniumselenium-chromedriver

解决方案


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;   
import org.openqa.selenium.InvalidArgumentException;

    WebDriver driver;
    Boolean success;
    ChromeOptions options = new ChromeOptions();

    try {
    options.addArguments("--user-data-dir=Profile");
    success = true;
    }
    catch (InvalidArgumentException invArgEx) {
    success = false;
    }

    if (success) {
    driver = new ChromeDriver(options);
    }

推荐阅读