Selenium Java关闭浏览器

在学习selenium的过程中发现一个问题,各种博客/教程都是教人用selenium的quit()和close()方法关闭浏览器。

但这不是我要的结果。这两个方法的前提是,用webdriver打开浏览器,执行脚本之后再关闭已经用webdriver打开的浏览器。

我的前提条件:在用webdriver打开浏览器之前先检查是否有浏览器已经打开,如果有,先关闭这些浏览器,然后执行webdriver脚本。

这个也是借鉴于HP QTP(HP UFT),当初QTP遇到已经有浏览打开就不知道哪个浏览器是它要运行的,所以每次在运行qtp之前先关闭所有浏览器。

虽然selenium不存在这个问题,但还是习惯每次运行selenium脚本之前关闭所有浏览器。

现在已经被MF收购了,该叫MF UFT了。MF于2018年收购了HP的UFT和loadrunner。

据说MF还租用了之前HP在上海张江高科金科路VIA2626号?的办公室。

回到正题,以下思路就是用java rumtime执行windows命令查找进程/关闭进程。

总感觉这不是最好的方法,但却是我目前知道的唯一方法(不知道selenium到底有没有自己的方法)。

贴上代码,以下代码只是关闭firefox,后期会继续完善:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class WindowsProcess {

    public static void main(String[] args) throws InterruptedException {
        WindowsProcess winp = new WindowsProcess();
        winp.killProcess("firefox.exe");
    }

    public void killProcess(String processName) throws InterruptedException {
        try {
            String line;
            Process p = Runtime.getRuntime().exec("tasklist.exe");
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                System.out.println(line);
                if (line.contains("firefox.exe")) {
                    System.out.println("Firefox is found.");
                    Runtime.getRuntime().exec("taskkill /F /IM " + processName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/majestyking/p/10289509.html