如何使用selenium在PhantomJS中设置代理身份验证?

时间:2014-11-14 13:53:14

标签: java proxy selenium-webdriver webdriver phantomjs

我在java中运行这个简单的selenium测试:

public static void main(String[] args){
    WebDriver driver = new PhantomJSDriver();
    driver.get("http://www.google.com");
    WebElement element = driver.findElement(By.id("gbqfif"));
    element.sendKeys("cheese");
    element.submit();
    System.out.println("Titulo:"+driver.getTitle());
    driver.quit();
}

但是在我的办公室需要代理身份验证,我不知道如何设置它。

我必须将我的用户和密码放在某处。

你可以帮帮我吗?

1 个答案:

答案 0 :(得分:16)

PhantomJS使用从命令行(docs)设置的三个代理选项。

  
      
  • --proxy=address:port指定要使用的代理服务器(例如--proxy=192.168.1.42:8080)。
  •   
  • --proxy-type=[http|socks5|none]指定代理服务器的类型(默认为http)。
  •   
  • --proxy-auth指定代理的身份验证信息,例如--proxy-auth=username:password)
  •   

要使用这些,您必须将它们添加到DesiredCapabilities地图(如this答案中所示):

ArrayList<String> cliArgsCap = new ArrayList<String>();
cliArgsCap.add("--proxy=address:port");
cliArgsCap.add("--proxy-auth=username:password");
cliArgsCap.add("--proxy-type=http");
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
capabilities.setCapability(
    PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
WebDriver driver = new PhantomJSDriver(capabilities);