Open Tor Browser:
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();
}
Open Firefox with some configurations:
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);
Close browsers. Note that if you plan on doing a lot of closing and reopening (useful in obtaining a new IP address), I advise setting the profile preference toolkit.startup.max_resumed_crashes to a high value like 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 firefoxIsRunning = 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")) {
firefoxIsRunning = true;
break;
}
}
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return firefoxIsRunning;
}