当我想关闭所有正在运行的Firefox时遇到问题,我只能关闭一个窗口。 例如这样: 我有一个程序,当我运行firefox时,它会打开,然后结束它会关闭firefox,但是问题是当我的程序尚未运行但已经先运行了firefox时,因此我想在程序运行firefox之前制作要检查是否已经首先打开了Firefox,如果要打开,则必须关闭它,该怎么办?
这是一些示例代码
private static WebDriver driver;
private static WebDriverWait wait;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.gecko.driver", DRIVER_LOCATION);
driver = new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 30, 100);
runJourneys();
}
这是关闭Firefox的最后一个过程
driver.quit();
我的问题是:
答案 0 :(得分:2)
要检查Firefox是否正在运行,请按照以下步骤操作:
public boolean isFirefoxRunning(){
boolean flag = false;
try {
Process proc = Runtime.getRuntime().exec("wmic.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
oStream.write("process where name='firefox.exe'");
oStream.flush();
oStream.close();
while ( input.readLine() != null) {
flag= true;
break;
}
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
您可以编写自己的实用程序功能来关闭所有Firefox实例/窗口,如下所示:
public void closeAllFirefoxInstances(){
try {
Runtime.getRuntime().exec("TASKKILL /F /IM firefox.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:2)
由于您尚未在下方指定可运行的操作系统,因此您可以找到一种无需第三方应用即可帮助您完成所需任务的方法。
executeCommand
- 为了从 Java 中终止一个进程,您可能已经猜到了,您需要在命令行中打开一个进程 - 下面是使用 ProcessBuilder
实现的。在当前形式中,该方法使用可变参数 - 因此您可以传递多个参数。
killBrowserProcess
- 正在获取当前操作系统并执行特定的 cli 命令来终止该进程 - 该方法不仅可以用于终止浏览器,还可以用于各种情况。
public void killBrowserProcess(String browserName){
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {
String windowsCmdLine = "taskkill /f /IM " + browserName + ".exe";
executeCommand(windowsCmdLine);
} else {
if (osName.contains("mac") || osName.contains("linux")) {
executeCommand("/usr/bin/killall -KILL " + browserName);
}
}
}
private void executeCommand(String... args) {
ProcessBuilder pb;
Process pc;
try {
for (String arg : args) {
pb = new ProcessBuilder(arg.split(" "));
pc = pb.start();
pc.waitFor();
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
//handle the exception
}
}
答案 2 :(得分:0)
driver.close();-这仅用于关闭正在处理的打开标签
driver,quit(); -这是从浏览器退出(结束会话,标签,弹出窗口)