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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM