Phantomjs 一些简单实用

  Phantomjs是一个基于webkit的服务器端JavaScirpt API。它全面支持web而不需要浏览器支持,并且原生支持web的各种标准:DOM处理,CSS选择器,JSON,Canvas和SVG。可以用于页面自动化、网络检测、网页截屏、无界面测试等。

  1、使用

  新建一个hi.js文件,里面写入js脚本,并且以phantom.exit();结尾, 执行DOS命令:phantomjs hi.js即可执行文件内脚本内容。

  2、参数处理

  参考phantomjs安装目录下examples中的arguments.js,DOS命令:phantomjs examples/arguments.js foo bar baz

  它将输出 :

    0: foo
    1: bar
    2: baz

  3、页面截图

  参考代码(将请求www.baidu.com网站并将截图保存成baidu.png):

var page = require('webpage').create();
page.open('http://www.baidu.com', function () {
  page.render('html/baidu.png');
  phantom.exit();
});

  4、Cookie处理

var page = require('webpage').create();

var fs = require('fs');
phantom.addCookie({
  'name' : 'province',
  'value': 'provinceName%22%3A%22%u5317%u4EAC',
  'domain': 'baidu.com'
});
phantom.addCookie({
  'name' : 'addrDetail',
  'value': '%7B%22detail%22%3A%22%u5317%u4EAC%22%2C%22detailId%22%3A2%2C%22detailCode%22%3A110000%7D',
  'domain': 'baidu.com'
});
page.open('http://www.baidu.com', function(status){
  if(status !== 'success'){
    console.log('Unable to post!');
  }else{ // 将页面保存成本地文件,并将所有script脚本替换为空字符,
    fs.write('html/baidu.html',page.content.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gm,""),'w');
  }
  phantom.exit();
});

  5、文件处理

var filePath = 'test.js';//文件路径
  var fs = require("fs");
  //判断文件是否存在,是文件还是文件夹
  if( fs.exists(filePath) && fs.isFile(filePath) ) {
    var ins = fs.open(filePath, 'r');//打开文件
    while(!ins.atEnd()) {//循环读取文件内容
    var buffer = ins.readLine();//一行行的读取
    console.log(buffer);
  }
}

  

posted @ 2016-06-12 15:21  雨之殇  阅读(1827)  评论(0编辑  收藏  举报