如何在 Java 中使用 selenium 在 Tor 浏览器中打开网页?

问题描述

我使用 selenium 服务器文件作为外部库,我可以打开 Tor 浏览器,但似乎无法自动打开 Tor 浏览器以打开 google 等网站。

下面的代码运行 Tor 浏览器和 Firefox 浏览器,但在 Firefox 浏览器中打开 https://www.google.com 而不是 Tor 浏览器。如何在 Tor 浏览器而不是 Firefox 浏览器中自动打开 google 和其他命令?

public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.gecko.driver","C:\\Users\\vee\\Downloads\\geckodriver-v0.29.0-win64(1)\\geckodriver.exe");
    File torProfileDir = new File("C:\\Users\\vee\\Desktop\\Tor browser\\browser\\Torbrowser\\Data\\browser\\profile.default");
    FirefoxBinary binary = new FirefoxBinary(new File("C:\\Users\\vee\\Desktop\\Tor browser\\browser\\firefox.exe"));
    FirefoxProfile torProfile = new FirefoxProfile(torProfileDir);
    torProfile.setPreference("webdriver.load.strategy","unstable");

    try {
        binary.startProfile(torProfile,torProfileDir,"");
    } catch (IOException e) {
        e.printstacktrace();
    }
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("network.proxy.type",1);
    profile.setPreference("network.proxy.socks","127.0.0.1");
    profile.setPreference("network.proxy.socks_port",9150);

    FirefoxDriver driver = new FirefoxDriver();

    Thread.sleep(10000);

    driver.get("http://www.google.com");

    Thread.sleep(500000);

    killFirefox();

    System.out.println("URL has been loaded successfully");
}
private static void killFirefox() {
    Runtime rt = Runtime.getRuntime();
    try {
        rt.exec("taskkill /F /IM firefox.exe");
        while (processIsRunning("firefox.exe")) {
            Thread.sleep(100);
        }
    } catch (Exception e) {
        e.printstacktrace();
    }
}
private static boolean processIsRunning(String process) {
    boolean processIsRunning = false;
    String line;
    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='" + process + "'");
        oStream.flush();
        oStream.close();
        while ((line = input.readLine()) != null) {
            if (line.toLowerCase().contains("caption")) {
                processIsRunning = true;
                break;
            }
        }
        input.close();
    } catch (IOException e) {
        e.printstacktrace();
    }
    return processIsRunning;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)