因为 Tor Browser Bundle 只是 Firefox 的补丁版本,所以似乎应该可以使用FirefoxDriver
使用 Tor 浏览器。这是我到目前为止所尝试过的:
String torPath = "C:\\Users\\My User\\Desktop\\Tor Browser\\Start Tor Browser.exe";
String profilePath = "C:\\Users\\My User\\Desktop\\Tor Browser\\Data\\Browser\\profile.default";
FirefoxProfile profile = new FirefoxProfile(new File(profilePath));
FirefoxBinary binary = new FirefoxBinary(new File(torPath));
FirefoxDriver driver = new FirefoxDriver(binary, profile);
driver.get("http://www.google.com");
这会导致打开一个空白的 Tor 浏览器页面,并显示一条弹出消息:无法加载您的 Firefox 配置文件。它可能丢失或无法访问。
我知道该配置文件有效/兼容,因为我可以使用以下命令成功启动浏览器和配置文件:
binary.startProfile(profile, profilePath, ""));
但是,我不知道如何向以这种方式打开的浏览器发送命令。
我发现了类似的问题,但我专门寻找 Java 解决方案,最好在 Windows 上进行测试。
我正在使用可以下载的独立 Selenium 库here http://www.seleniumhq.org/download/以及可以下载的 Tor 浏览器捆绑包here https://www.torproject.org/download/download.
由于 Tor Browser Bundle 不允许我使用 WebDriver 扩展,我找到了一种解决方法,从常规 Firefox 浏览器运行 Tor。通过这种方法,只要 Tor 浏览器打开,您就可以通过常规 Firefox 浏览器使用 Tor。
-
打开 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();
}
-
打开火狐浏览器一些配置:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)