因为Tor浏览器软件包不让我使用WebDriver扩展,我发现一个解决方法,我从一个常规的Firefox浏览器运行Tor。使用这种方法,只要Tor浏览器打开,您可以使用Tor与常规的Firefox浏览器。
>打开Tor浏览器:
File torProfileDir = new File(
"...\\Tor Browser\\Data\\Browser\\profile.default");
FirefoxBinary binary = new FirefoxBinary(new File(
"...\\Tor Browser\\Start Tor Browser.exe"));
FirefoxProfile torProfile = new FirefoxProfile(torProfileDir);
torProfile.setPreference("webdriver.load.strategy", "unstable");
try {
binary.startProfile(torProfile, torProfileDir, "");
} catch (IOException e) {
e.printStackTrace();
}
>使用一些配置打开Firefox:
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 = new FirefoxDriver(profile);
>关闭浏览器请注意,如果您计划进行大量关闭和重新打开(有助于获取新的IP地址),我建议将配置文件首选项toolkit.startup.max_resumed_crashes设置为9999这样的高值。
private 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 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;
}