如何使用Selenium webdriver和Java为firefox设置代理?

System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.18.0-win64\\geckodriver.exe"); Proxy p = new Proxy(); p.setSocksProxy("83.209.94.87:35923"); DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(CapabilityType.PROXY, p); WebDriver driver = new FirefoxDriver(cap); driver.get("https://www.google.com.au"); 

此代码位于main方法内。 当我运行此代码时,启动了Firefox,但未遵循google url,并且代理未设置为我在上面的代码中指定的代理。 我怎样才能解决这个问题?

 public static void main(String[] args) throws InterruptedException, IOException, UnsupportedEncodingException { while (true) { System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.18.0-win64\\geckodriver.exe"); WebDriver driver; String PROXY = "83.209.94.87:35923"; //Bellow given syntaxes will set browser proxy settings using DesiredCapabilities. Proxy proxy = new Proxy(); proxy.setAutodetect(false); proxy.setProxyType(Proxy.ProxyType.MANUAL); proxy.setSocksProxy(PROXY); DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(CapabilityType.PROXY, proxy); //Use Capabilities when launch browser driver Instance. driver = new FirefoxDriver(cap);` 

因为一个bug你现在不能使用Proxy对象。 您应该使用以下代码

  FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("network.proxy.type", 1); profile.setPreference("network.proxy.socks", "83.209.94.87"); profile.setPreference("network.proxy.socks_port", 35923); FirefoxDriver driver = new FirefoxDriver(profile); driver.get("https://www.ipinfo.io"); 

该错误在https://github.com/mozilla/geckodriver/issues/764上讨论,你可以看到Marionette驱动程序在后面的链接中做了什么

https://dxr.mozilla.org/mozilla-central/source/testing/marionette/session.js#155

所以上面的代码只复制相同的内容

在Selenium 3.14.2,Firefox 62,C#.NET 4.5中工作

 FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"GeckoDriver19", "geckodriver.exe"); service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.SetPreference("network.proxy.type", 1); firefoxOptions.SetPreference("network.proxy.socks", "127.0.0.1"); firefoxOptions.SetPreference("network.proxy.socks_port", 1080); IWebDriver driver = new FirefoxDriver(service, firefoxOptions); driver.Navigate().GoToUrl("https://www.hbus.com/register");