Phantomjs實(shí)用代碼段(持續(xù)更新中……)
一、下載
二、解壓安裝包
直接解壓即可
三、配置環(huán)境變量
找到高級系統(tǒng)設(shè)置,打開它,出現(xiàn)以下圖。點(diǎn)擊環(huán)境變量。
分別點(diǎn)擊編輯按鈕
分別新建添加當(dāng)初的解壓路徑,到bin文件夾。點(diǎn)擊確定。
這樣,環(huán)境變量配置好了,可以再命令行工具直接使用phantomjs命令。
四、代碼段
新建一個(gè)JS文件,如:main.js
執(zhí)行命令:phantomjs main.js
1、打印指定網(wǎng)址標(biāo)題
var page = require('webpage').create();
phantom.outputEncoding="gbk";
page.open("https://url.163.com/EWS", function(status) {
console.log("Status: " + status);
if ( status === "success" ) {
console.log(page.title)
} else {
console.log("Page failed to load.");
}
phantom.exit(0);
});
2、生成網(wǎng)頁截圖
var page = require('webpage').create();
page.open('https://maomin.blog.csdn.net/', function() {
page.render('github.png');
phantom.exit();
});
3、將網(wǎng)頁轉(zhuǎn)換為PDF
var wpage = require('webpage').create();
var url = "https://en.wikipedia.org/wiki/Main_Page";
var output = "test.pdf";
wpage.paperSize = {
width: screen.width+'px',
height: '1500px',
margin: {
'top':'50px',
'left':'50px',
'rigtht':'50px'
},
orientation:'portrait',
header: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h5>Header <b>" + pageNumber + " / " + nPages + "</b></h5>";
})
},
footer: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h5>Footer <b>" + pageNumber + " / " + nPages + "</b></h5>";
})
}
}
wpage.open(url, function (status) {
if (status !== 'success') {
console.log('Page is not opening');
phantom.exit();
} else {
wpage.render(output);
phantom.exit();
}
});
未完待續(xù)……
作者:Vam的金豆之路
主要領(lǐng)域:前端開發(fā)
我的微信:maomin9761
微信公眾號:前端歷劫之路