Using Selenium WebDriver with Tor


SUBMITTED BY: cooller

DATE: Nov. 26, 2015, 12:35 p.m.

FORMAT: Text only

SIZE: 2.0 kB

HITS: 970

  1. Open Tor Browser:
  2. File torProfileDir = new File(
  3. "...\\Tor Browser\\Data\\Browser\\profile.default");
  4. FirefoxBinary binary = new FirefoxBinary(new File(
  5. "...\\Tor Browser\\Start Tor Browser.exe"));
  6. FirefoxProfile torProfile = new FirefoxProfile(torProfileDir);
  7. torProfile.setPreference("webdriver.load.strategy", "unstable");
  8. try {
  9. binary.startProfile(torProfile, torProfileDir, "");
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. Open Firefox with some configurations:
  14. FirefoxProfile profile = new FirefoxProfile();
  15. profile.setPreference("network.proxy.type", 1);
  16. profile.setPreference("network.proxy.socks", "127.0.0.1");
  17. profile.setPreference("network.proxy.socks_port", 9150);
  18. FirefoxDriver = new FirefoxDriver(profile);
  19. 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.
  20. private void killFirefox() {
  21. Runtime rt = Runtime.getRuntime();
  22. try {
  23. rt.exec("taskkill /F /IM firefox.exe");
  24. while (processIsRunning("firefox.exe")) {
  25. Thread.sleep(100);
  26. }
  27. }
  28. catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. private boolean processIsRunning(String process) {
  33. boolean firefoxIsRunning = false;
  34. String line;
  35. try {
  36. Process proc = Runtime.getRuntime().exec("wmic.exe");
  37. BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  38. OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
  39. oStream.write("process where name='" + process + "'");
  40. oStream.flush();
  41. oStream.close();
  42. while ((line = input.readLine()) != null) {
  43. if (line.toLowerCase().contains("caption")) {
  44. firefoxIsRunning = true;
  45. break;
  46. }
  47. }
  48. input.close();
  49. } catch (IOException ioe) {
  50. ioe.printStackTrace();
  51. }
  52. return firefoxIsRunning;
  53. }

comments powered by Disqus