WebDriver+PhantomJs爬虫运用(Java)

需要的添加的jar包及工具:我这里使用maven来构建项目,添加依赖如下:

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>3.2.0</version>
</dependency>  

PhantomJs工具到官网去下载:http://phantomjs.org/download.html

尽量都使用最新版本,不然会出现版本兼容的情况。

这里有一个已经写好的获取PhantomJSDriver的工具类

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/win/phantomjs.exe");//设置PhantomJs访问路径
  }
  DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
  //设置参数
  desiredCapabilities.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
  desiredCapabilities.setCapability("phantomjs.page.customHeaders.User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101   Firefox/50.0");
  if (Constant.isProxy) {//是否使用代理
    org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
    proxy.setProxyType(org.openqa.selenium.Proxy.ProxyType.MANUAL);
    proxy.setAutodetect(false);
    String proxyStr = "";
    do {
      proxyStr = ProxyUtil.getProxy();//自定义函数,返回代理ip及端口
    } while (proxyStr.length() == 0);
    proxy.setHttpProxy(proxyStr);
    desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
  }
  return new PhantomJSDriver(desiredCapabilities);
}

获取方式  

  try{
    WebDriver webDriver = PhantomJsUtil.getPhantomJs();
    webDriver.get(url);
    SleepUtil.sleep(Constant.SEC_5);
    PhantomJsUtil.screenshot(webDriver);
    WebDriverWait wait = new WebDriverWait(webDriver, 10);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id(inputId)));//开始打开网页,等待输入元素出现
    Document document = Jsoup.parse(webDriver.getPageSource());

    //TODO  剩下页面的获取就按照Jsoup获取方式来做

  }finally{
    if (webDriver != null) {
      webDriver.quit();
    }
  }

python版使用webdriver+PhantomJs爬虫使用,参考http://www.cnblogs.com/kuqs/p/6395284.html

 

posted @ 2017-05-03 16:54  释然的蛋  阅读(15114)  评论(4编辑  收藏  举报