phantomJS主要應用於網絡爬蟲,可以獲取網頁的內容及截圖,這裏簡單介紹下截圖
下載phantomJS應用
官網下載
http://phantomjs.org/download.html
這裏面有windows linux 等應用
我這邊先現在windows應用
解壓後是這樣的
運行
可以運行,直接上代碼
java代碼
public static void main(String[] args) throws IOException {
System.out.println("開始");
String BLANK = " ";
Process process = Runtime.getRuntime().exec(
"D:/Program Files/phantomjs-2.1.1-windows/bin/phantomjs.exe" + BLANK //你的phantomjs.exe路徑
+ "C:/Users/Administrator/Desktop/test1.js" + BLANK //就是上文中那段javascript腳本的存放路徑
+ "https://blog.csdn.net/nanyanglu/article/details/52671044#comments" + BLANK //你的目標url地址
+"C:/Users/Administrator/Desktop/cnblogs1111.png");//你的圖片輸出路徑
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String tmp = "";
System.out.println(reader.readLine());
if (reader != null) {
reader.close();
}
if (process != null) {
process.destroy();
process = null;
System.out.println("渲染成功...");
}
}
js代碼
var page = require('webpage').create(),
system = require('system'),
address, output, size;
if (system.args.length < 3 || system.args.length > 5) {
console.log('Usage: rasterize.js URL filename');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 1024, height: 1000 };
page.open(address, function (status) {
// 通過在頁面上執行腳本獲取頁面的渲染高度
var bb = page.evaluate(function () {
return document.getElementsByTagName('html')[0].getBoundingClientRect();
});
// 按照實際頁面的高度,設定渲染的寬高
page.clipRect = {
top: bb.top,
left: bb.left,
width: bb.width,
height: bb.height
};
// 預留一定的渲染時間
window.setTimeout(function () {
page.render(output);
page.close();
console.log('render ok');
}, 10000);
});
}
這樣就可以把整個頁面截取下來。
在linux下運行截取網頁
可以直接在linux上下載,根據自己系統是32位還是64位
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
壓縮包下載成功了,解壓
tar -xjf phantomjs-2.1.1-linux-x86_64.tar.bz2
驗證是否可以運行
如果運行的 phantomjs -v
出現以下錯誤:
bin/phantomjs: error while loading shared libraries: libfontconfig.so.1:
cannot open shared object file: No such file or directorybin/phantomjs: error while loading
shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
請在下面相對應的linux版本 運行以下命令
ubuntusudo apt-get install libfontconfig
centosyum install libXext libXrender fontconfig libfontconfig.so.1
運行通過,將phantomjs 設置爲全局的命令。
在截取圖片時值顯示圖片,不顯示文字(包括中文和英文)
linux中不顯示文字即沒有安裝相應的字體,我們安裝字體即可:
在centos中執行:yum install bitmap-fonts bitmap-fonts-cjk
在ubuntu中執行:sudo apt-get install xfonts-wqy
執行上述命令即ok