PhantmoJS是一个基于WebKit的服务器端JavaScript API。它全面支持Web而不需要浏览器支持,运行速度快,原生支持各种Web标准:DOM处理、CSS选择器、JSON、Canvas、SVG。PhantomJS是一个没有界面的浏览器,常被成为无头浏览器,它既有Firefox浏览器、Google的功能,又因为没有界面速度更快,占用的内存更小。
PhantomJS安装
安装下载地址:http://phantmojs.org/download.html,自行选择需要的版本下载解压,需要对PhantomJS配置环境变量。下载解压,文件夹中的example有很多官方的例子感兴趣的可以看看。
如果没有将phantomjs添加到环境变量,可以在bin文件夹下打开CMD输入phantomjs -v 查看版本号。
PhantomJS入门
创建一个hello.js文件,将下面的代码添加到该文件中:
console.log('hello eyujun');
phantom.exit();
然后在CMD命令行输入
phantomjs hello.js
就可以看到执行结果。console.log是js代码,最后需要终止phtanom,不然程序会一直运行。页面加载
通过PhantomJS,一个网页可以被加载,分析通过创建网页对象呈现。例如使用phantomjs访问鳄鱼君:/p>
var page=require('webpage').create(); //创建page对象
page.open('https://www.e1yu.com',function(status){ // 打开网页
console.log('Status:',status); //如果响应状态码为success
if (status==='success') {
page.render('eyujun.png'); //将当前页面保存为png图片
}
phantom.exit();
});
接着在CMD输入命令运行,这里我还是存放在hello.js文件中,直接运行,就会看到在当前目录下生成对应的png图片。
网页测速
测速代码存放在loadspeed.js文件
var page=require('webpage').create(); //创建page对象
system=require('system'), //获取系统对象system
t,url; //声明两个变量 时间 url
if (system.args.length===1){ //获取输入的url,等于1即没有url,退出
console.log('Usage: loadspeed.js URL')
phantom.exit();
}
t=Date.now();
url=system.args[1];
page.open(url,function(status){ // 打开网页
console.log('Status:',status); //如果响应状态码为success
if (status !== 'success') { //加载失败
console.log('fail to load the url');
}else{ //加载成功
t=Date.now()-t;
console.log('loading time '+t+'msec')
}
phantom.exit();
});
运行的时候输入phantomjs loadspeed.js https://www.e1yu.com
代码评估
评估网页中的JavaScript代码,可以使用evaluate。evaluate方法可以返回一个对象,返回值仅限于对象,不能包含函数。例如使用evaluate获取页面的标题。
var url ='https://www.e1yu.com';
var page=require('webpage').create();
page.open(url,function(status){
var title=page.evaluate(function(){
return document.title;
});
console.loge('page title is ',title);
phantom.exit();
});
屏幕截图
PhantomJS不仅可以将网页保存为png格式,还可以保存为jpg、gif、pdf格式。
var page=require('webpage').create(); //创建page对象
page.open('https://www.e1yu.com',function(status){ // 打开网页
console.log('Status:',status); //如果响应状态码为success
if (status==='success') {
page.render('eyujun.pdf');
page.render('eyujun.jpg');
}
phantom.exit();
});
对视图进行缩放和裁剪,主要用到page对象中的两个方法viewportSize和clipRect。
- viewportSize:视图大小,将打开的浏览器窗口进行缩放
- cliRect:剪裁矩形大小,需要四个参数,前两个是基准点,后两个参数是宽高
var page=require('webpage').create(); //创建page对象
page.viewportSize={width:1024,height:1024};
page.clipRect={top:0,left:0;width:1024,height:1024}
page.open('https://www.e1yu.com',function(status){ // 打开网页
console.log('Status:',status); //如果响应状态码为success
if (status==='success') {
page.render('eyujun.png');
}
phantom.exit();
});
网络监控
PhantomJS允许检验网络流量,所以它适合对网络行为和性能进行分析。
var url ='https://www.e1yu.com';
var page=require('webpage').create();
page.onResourceRequested=function(request){
console.log('request' +JSON.stringify(request,undefined,4));
};
page.onResourceReceived=function(response){
console.log('receive'_JSON.stringify(response,undefined,4));
}
page.open(url);
页面自动化
PhantomJS可加载处理一个网页,非常适合自动化处理。PhantomJS中标准JavaScript的DOM操作和CSS选择器都是生效的。例如,获取鳄鱼君网页某篇文章的内容:
var page=require('webpage').create(); //创建page对象
console.log('The default user agent is ' + page.settings.userAgent); //默认的UA
page.settings.userAgent ='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36';
page.open('https://www.e1yu.com/9957.html', function(status) {
if (status ! == 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
return document.getElementById('image_container').textContent;
});
console.log(ua);
}
phantom.exit();
});
常用模块和方法
常用模块包括pantom、webpage、system、fs
phantom
常用的5个方法:1.addCookie(object) 添加一个Cookie到CookieJar中
phantom.addCookie({
'name':'eyujun',
'age':'18'
});
2.clearCookies() 删除CookieJar中所有的Cookie信息
phantom.clearCookies();
3.deleteCookie() 删除指定名称的Cookie信息
phantom.deleteCookie('eyujun');
4.phantom.exit() 以指定的返回值退出程序
if (somethingIsWrong){
phantom.exit(1);
}else{
phantom.exit(0);
}
5.phantom.injectJs 注入外部的js
var wasSuccessful=phantom.jnjectJs('hell.js');
webpage
常用的includeJs、open方法,onInitialized、onLoadFinished回调方法
1.includeJs(url,callback) {void}
var webPage = require('webpage');
var page = webPage.create();
page.includeJs(
'https://www.e1yu.com/wp-content/themes/vieu/static/js/loader.js',
function() {
(page.evaluate(function() {
var $loginForm = $('form# login');
$loginForm.find('input[name="username"]').value('phantomjs');
$loginForm.find('input[name="password"]').value('12345');
}))
}
);
open(url, callback) {void}、
open(url, method, callback) {void}、
open(url, method, data, callback) {void}、
open(url, settings, callback){void}
open(url, method, data, callback)中url为链接,method为GET或者POST请求,data为附加的数据,callback为回调函数
var webPage = require('webpage');
var page = webPage.create();
var postBody = 'name=name&pd=password';
page.open('http://www.e1yu.com/', 'POST', postBody, function(status) {
console.log('Status: ' + status);
});
open(url, settings, callback)中url为链接,setting为对请求头和内容的设置,callback为回调函数
var webPage = require('webpage');
var page = webPage.create();
var settings = {
operation: "POST",
encoding: "utf8",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
some: "data",
another: ["custom", "data"]
})
};
page.open('http://www.e1yu.com/', settings, function(status) {
console.log('Status: ' + status);
});
onInitialized是回调方法,在webpage对象被创建之后,url被加载之前被调用,主要是用来操作一些全局变量
var webPage = require('webpage');
var page = webPage.create();
page.onInitialized = function() {
page.evaluate(function() {
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM content has loaded.');
}, false);
});
};
onLoadFinished是回调方法,在页面加载完成之后调用,方法还有一个参数status。如果加载成功status为success,否则为fail。webpage中open方法就是用这个方法作为回调函数。
var webPage = require('webpage');
var page = webPage.create();
page.onLoadFinished = function(status) {
console.log('Status: ' + status);
};
system
system模块只有属性,没有方法1.args 命令行中输入的参数,是一个列表
var system=require('system');
var args=system.args;
if (args.length>1){
args.forEach(function(arg,i){
console.log(i+':'+arg);
});
}
2.env 系统变量,键值对列表
var system=require('system');
var env=system.env;
Object.keys(env).forEach(function(key){
console.log(key,env[key]);
});
3.os 操作系统的信息
var system=require('system');
var os=system.os;
console.log(os.architecture);
console.log(os.name);
console.log(os.version);
4.pid 当前执行phantomjs的进程号
var system=require('system');
ver pid=system.pid;
console.log(pid);
5.platform 平台名称
var system=require('system');
console.log(system.platform)
fs
fs模块全称为File System,主要是对文件系统进行操作。1.touch 创建一个空文件
var fs=require('fs');
var path= 'test.txt';
fs.touch(path);
phantom.exit();
2.exists 判断文件是否存在
var fs=require('fs');
var path= 'test.txt';
if (fs.exists(path)){
console.log('file already exist');
}else{
console.log(' file does not exist ');
}
phantom.exit();
3.read 读文件
var fs =require('fs');
var content=fs.read('file.txt');
console.log('read data:',content);
phantom.exit();
4.write 写文件
var fs=require('fs');
var path='file.txt';
var content='hello eyujun';
fs.write(path,content,'w');
phantom.exit();
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
评论(2)
你这学的可真杂啊!
哎!最近有点迷茫,找不到方向了