java調用phantomjs爬取動態網頁

1、下載phantomjs。phantomjs的下載地址:http://npm.taobao.org/dist/phantomjs/

2、將壓縮包解壓到自己選擇的一個地址(我選的是D:\software\phantomjs)

3、編寫js文件,我將js文件放在D:\software\phantomjs\codes.js,該路徑會在java程序中以絕對路徑調用。

//codes.js
system = require('system')
address = system.args[1];//獲得命令行第二個參數 接下來會用到
//console.log('Loading a web page');
var page = require('webpage').create();
var url = address;
//console.log(url);
page.open(url, function (status) {
    //Page is loaded!
    if (status !== 'success') {
        console.log('Unable to post!');
    } else {
        //console.log(page.content);
		//var title = page.evaluate(function() {
		//	return document.title;//示範下如何使用頁面的jsapi去操作頁面的
		//	});
		//console.log(title);
		
		console.log(page.content);
	}	
    phantom.exit();
}); 

4、編寫java程序調用

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JSUtil {
	
	/*
	 *  如果要更換運行環境,請注意exePath最後的phantom.exe需要更改。因爲這個只能在window版本上運行。前面的路徑名  
      *也需要和exePath裏面的保持一致。否則無法調用  
	 */
    private static String projectPath ="D:"+File.separator+"software"+File.separator+"phantomjs";
    private static String jsPath = projectPath + File.separator + "codes.js";  
    private static String exePath = projectPath + File.separator + "phantomjs-2.1.1-windows" + File.separator + "bin" + File.separator  
            + "phantomjs.exe";  

	public static void main(String[] args) throws IOException {
		 // 測試調用。傳入url即可  
        String html = getParseredHtml2("https://www.vmall.com/product/10086134839130.html");  
        System.out.println("html: " + html);  
	}
	
	   // 調用phantomjs程序,並傳入js文件,並通過流拿回需要的數據。  
    public static String getParseredHtml2(String url) throws IOException  
    {  
        Runtime rt = Runtime.getRuntime();  
        Process p = rt.exec(exePath + " " + jsPath + " " + url);  
        InputStream is = p.getInputStream();  
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));  
        StringBuffer sbf = new StringBuffer();  
        String tmp = "";  
        while((tmp = br.readLine())!=null){
            sbf.append(tmp);
        }
        //System.out.println(sbf.toString());
        return sbf.toString();
    }
}

5、注意事項,因爲phantomjs是等js函數執行完,再將整個界面源代碼轉換爲字符串,所以速度會有點慢。對於亂碼問題:BufferedReader br = new BufferedReader(new InputStreamReader(is,“UTF-8”));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章