Java 在 Tor 中使用 Selenium WebDriver

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22978074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:43:14  来源:igfitidea点击:

Using Selenium WebDriver with Tor

javafirefoxselenium-webdrivertortor-browser-bundle

提问by Joel Christophel

Because Tor Browser Bundle is just a patched version of Firefox, it seems that it should be possible to use a FirefoxDriverwith Tor Browser. This is what I've tried so far:

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

This results in a blank Tor Browser page opening with a popup message: Your Firefox profile cannot be loaded. It may be missing or inaccessible.

这会导致打开一个空白的 Tor 浏览器页面,并显示一条弹出消息:无法加载您的 Firefox 配置文件。它可能丢失或无法访问。

I know that the profile is valid/compatible because I can successfully start the browser and profile with:

我知道配置文件有效/兼容,因为我可以通过以下方式成功启动浏览器和配置文件:

binary.startProfile(profile, profilePath, ""));

I don't know how to send commands to a browser opened in such a manner, however.

但是,我不知道如何向以这种方式打开的浏览器发送命令。

I've found similar questions, but I'm specifically looking for a Java solution, preferably tested on Windows.

我发现了类似的问题,但我特别在寻找 Java 解决方案,最好在 Windows 上进行测试。

I'm using a standalone Selenium library that can be downloaded hereand the Tor Browser Bundle that can be downloaded here.

我使用的是独立硒库,可以下载在这里和Tor浏览器套件,可以下载在这里

采纳答案by Joel Christophel

Because Tor Browser Bundle wasn't letting me use the WebDriver extension, I found a workaround in which I ran Tor from a regular Firefox browser. With this method, as long as the Tor Browser is open, you can use Tor with a regular Firefox browser.

因为 Tor Browser Bundle 不允许我使用 WebDriver 扩展,所以我找到了一种解决方法,我在其中从常规 Firefox 浏览器运行 Tor。使用这种方法,只要 Tor 浏览器处于打开状态,您就可以在常规 Firefox 浏览器中使用 Tor。

  • 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 Firefoxwith 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_crashesto 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 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;
    }
    
  • 打开 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;
    }
    

回答by Dan Snell

I would try specifying the path of one of the existing profiles and initialize your profile instance for Tor so your code would look something like:

我会尝试指定现有配置文件之一的路径并为 Tor 初始化您的配置文件实例,以便您的代码如下所示:

String torPath = "..\Tor Browser\Browser\firefox.exe";
String profilePath = "..\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");

I didn't try this since I don't have WebDriver setup at home, but this should allow you to specify a profile.

我没有尝试这个,因为我家里没有 WebDriver 设置,但这应该允许你指定一个配置文件。

回答by Dan Snell

I downloaded TorBrowser and I was able to call it without any problem, with the following code (it's Mac OS). So I think there shouldn't be any problem about compatibility between the firefox webdriver and the latest version of Tor Browser.

我下载了 TorBrowser 并且可以使用以下代码(它是 Mac OS)毫无问题地调用它。所以我认为firefox webdriver和最新版本的Tor Browser之间的兼容性应该没有任何问题。

String torPath = "/Volumes/DATA/Downloads/Tor.app/Contents/MacOS/TorBrowser.app/Contents/MacOS/firefox";
String profilePath = "/Users/mimitantono/Library/Application Support/Firefox/Profiles/1vps9kas.default-1384778906995";
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/webhp?complete=1&hl=en");

I know that you already tested the path of your profile with binary.startProfilebut I think you could try again to use slash instead of backslash to specify the path, cross check whether that file exists -> profile.default, and to use absolute path instead of relative -> ../.

我知道您已经测试了您的配置文件的路径,binary.startProfile但我认为您可以再次尝试使用斜杠而不是反斜杠来指定路径,交叉检查该文件是否存在 -> profile.default,并使用绝对路径而不是相对 -> ../

回答by Татьяна Алиева

This code also is working pretty good in ubuntu. Here is an example (JUnit4):

这段代码在 ubuntu 中也运行良好。这是一个示例(JUnit4):

package qa2all;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;


public class HTMLUnit {
    private WebDriver driver;
    private String baseUrl;
    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
        //driver = new HtmlUnitDriver();    
        //driver = new FirefoxDriver();
        String torPath = "/home/user/Dropbox/Data/TorBrowser/Linux/32/start-tor-browser";
        String profilePath = "/home/user/Dropbox/Data/TorBrowser/Linux/32/TorBrowser/Data/Browser/profile.default/";
        FirefoxProfile profile = new FirefoxProfile(new File(profilePath));
        FirefoxBinary binary = new FirefoxBinary(new File(torPath));
        driver = new FirefoxDriver(binary, profile);        
        baseUrl = "https://qa2all.wordpress.com";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testUntitled() throws Exception {
        driver.get(baseUrl + "/");

    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private void fail(String verificationErrorString) {
        // TODO Auto-generated method stub

    }
}

回答by serv-inc

If you mostly care about remote-controlling a browser using Tor (and would maybe prefer to use the Tor Browser instead of vanilla Firefox), you can use Mozilla's Marionette. Use like

如果您最关心使用 Tor 远程控制浏览器(并且可能更喜欢使用 Tor 浏览器而不是 vanilla Firefox),您可以使用 Mozilla 的Marionette。使用喜欢

To use with the Tor Browser, enable marionette at startup via

要与 Tor 浏览器一起使用,请在启动时通过以下方式启用牵线木偶

Browser/firefox -marionette

(inside the bundle). Then, you can connect via

(在捆绑包内)。然后,您可以通过连接

from marionette import Marionette
client = Marionette('localhost', port=2828);
client.start_session()

and load a new page for example via

并加载一个新页面,例如通过

url='http://mozilla.org'
client.navigate(url);

For more examples, there is a tutorialalong with more documentation.

有关更多示例,有一个教程以及更多文档。

(copy)

(复制)