java爬虫使用tor,java – 使用Selenium WebDriver与Tor

因为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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值