Java,selenium平台下PhantomJS配置隧道转发代理

Outshine 2018-11-23 | 阅读 5702

开发爬虫程序,免不了要使用代理,除了使用IP高匿代理,最近流行一种隧道转发代理,HTTP隧道基于HTTP协议,无须切换IP,连接某个代理服务器后,每一个请求都是一个随机IP,按并发数计费。

 

最近手头有个项目,要用到PhantomJS无头浏览器,下面的代码是在Java selenium环境下使用PhantomJS进行隧道转发代理的详细配置。

    public static WebDriver getPhantomJs() {
//  String osname = System.getProperties().getProperty("os.name");
//  if (osname.equals("Linux")) {//判断系统的环境win or Linux
//   System.setProperty("phantomjs.binary.path", "/usr/bin/phantomjs");
//  } else {
//   System.setProperty("phantomjs.binary.path", "./phantomjs/bin/phantomjs.exe");//设置PhantomJs访问路径
//  }
//     DesiredCapabilities caps = new DesiredCapabilities();
        DesiredCapabilities caps = DesiredCapabilities.phantomjs();
//        //ssl证书支持
        caps.setCapability("acceptSslCerts", false);
//        //截屏支持
        caps.setCapability("takesScreenshot", false);
//        //css搜索支持
        caps.setCapability("cssSelectorsEnabled", true);
//        //js支持
        caps.setJavascriptEnabled(true);
//        //驱动支持
        caps.setCapability("phantomjs.page.customHeaders.Authorization", "Basic WmU2STVtMEh3Mk5scXRnNzpMeW9GOVhBbE8wSm5DNnUw");
//        caps.setCapability("phantomjs.page.customHeaders.Proxy-Authorization",new MayiHttpClientProxy().getAuthHeader());
        caps.setCapability("phantomjs.page.settings.userAgent", CrawlerUtil.getRandomAgent());
        caps.setCapability("phantomjs.page.settings.loadImages", false);
        caps.setCapability("phantomjs.page.settings.disk-cache", false);
        caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, exePath);
       
  ArrayList<String> cliArgsCap = new ArrayList<String>();
        cliArgsCap.add("--web-security=false");
//        cliArgsCap.add("--ssl-protocol=any");
        cliArgsCap.add("--ignore-ssl-errors=true");
//        cliArgsCap.add("--load-plugins=yes");
//        cliArgsCap.add("--proxy=transfer.mogumiao.com:9001");
//        cliArgsCap.add("--proxy=s4.proxy.mayidaili.com:8123");
//        cliArgsCap.add("--proxy=http-pro.abuyun.com:9010");
//        cliArgsCap.add("--proxy-auth=H0H4A10X507VI27P:1F96A41C44781F14");
//        cliArgsCap.add("--proxy-auth=Ze6I5m0Hw2Nlqtg7:LyoF9XAlO0JnC6u0");
//        cliArgsCap.add("--proxy-type=https");
//  cliArgsCap.add("--disk-cache=true");
        cliArgsCap.add("--webdriver-loglevel=NONE");
        caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS,cliArgsCap);
//        if(webDriver==null){
//         webDriver = new PhantomJSDriver(caps);
//         webDriver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
//        }
        return new PhantomJSDriver(caps);
    }