phantomjs学习笔记


前一阵子入手了phantomjs 学起来甚爽

phantomjs的wiki    https://github.com/ariya/phantomjs/wiki

api https://github.com/ariya/phantomjs/wiki/API-Reference#wiki-webpage-url

介绍。。来自网易 。。

PhantomJS便是这么一个为自动化而生的利器,它本质上是一个基于webkit内核的无界面浏览器,并可使用JavaScript或CoffeeScript进行编程。由于没有界面,它的使用就有点像curl, lynx之类的命令行式文本浏览器。但PhantomJS远不是文本浏览器那么简单,由于它是基于webkit内核的,因此拥有的完善的Javascript解析、页面渲染功能,你完全可用它来模拟一个现代浏览器在加载网页时所做的各种事件。

其实说白了就是个无头浏览器。可以轻松的跑js,而且可以通过各种api采集页面的请求跟响应细节。

由于本人是实战型的。。所以通过分析demo来学习phantomjs吧~

安装程序 http://phantomjs.org/download.html

安装好以后,安装包下面会解压出一大堆文件来。其中phantomjs.exe 就是这个可执行文件。

node_modules就是一些nodejs的模块,是为了方便http,文件api等而用的。

examples是很多的demo,从这些demo入手。

demo的介绍在这里:

https://github.com/ariya/phantomjs/wiki/Examples

可以看到每个demo都是对应某种功能,或者是学习语法的。

打开命令行工具进入到phantomjs目录下后,我们可以在这里写代码了。。 新建一个js文件,输入

var t = 10, interval = setInterval(function(){ if ( t > 0 ) { console.log('hello world'+t--); } else { console.log("BLAST OFF!"); phantom.exit(); } }, 1000);

代码很简单,注意结束程序要用

phantom.exit()

来个稍微好玩点的吧,有时候你写了个ui效果,但是手头没有浏览器,咋办。。。(这个可能性貌似不大,只是娱乐一下)

var page = require('webpage').create();//“建造”一个页面 page.viewportSize = { width: 400, height : 400 };//设置“虚拟”页面大小 page.content = '<html><body><div id="demo" ></div></body></html>';//不解释。。 page.evaluate(function() {//重要,执行js语句 var el = document.getElementById('demo'); el.style.cssText = "width: 150px;height: 80px;border: 2px solid #f36;background: #ccc;border-radius: 10px 15px 20px 30px / 20px 30px 10px 15px;" }); page.render('border.png');//渲染结果输出到文件里。 phantom.exit();

运行后你发现目录多出来一张图片。。而这张图片正是不规则圆角的图片。。。

虽然phantomjs没有界面,但他完全是一个浏览器,因此他可以轻松解析css与js,并渲染出来。而渲染出来这个图片,可以用render 看到。

这里有几个非常重要的,属于webpage系列的api出现了 。

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

属于webpage module ,这可以说,我们打开了一个“虚拟”浏览器

在webpage下面的api里,可以设置 视口大小(viewportSize),渲染出来的图片大小(paperSize),页面内容(content),cookie(cookies)等等。甚至可以利用setting api 设置ua,设置是否启用js。。。

page同样也能调用 phantomjs  function部分,这里我们用到了两个核心方法

render(filename) {void}

Renders the web page to an image buffer and saves it as the specified filename.

它支持把页面输出成一张图片,支持jpg,gif,png,pdf格式,是我们截图的好工具。

evaluate(function, arg1, arg2, ...) {object}

Evaluates the given function in the context of the web page. The execution is sandboxed, the web page has no access to the phantom object and it can’t probe its own setting.

执行一个js函数,这个js函数在沙箱里。。不过貌似没找到是啥时候执行的

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures, functions, DOM nodes, etc. will not work!

这一段很关键,这个函数的参数必须是一个对象,而且这个对象是那种比较原始的- – 判别规则是 这个对象可以被JSON序列化。

因此他说了,闭包,传程序,dom节点均不会生效。。

但是里面当然可以随便写了~ 上面我用id选择器取元素,之后设置了cssText。

includeJs(url, callback) {void}

Includes external script from the specified url (usually a remote location) on the page and executes the callback upon completion.

Example:

page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() { /* jQuery is loaded, now manipulate the DOM */ });

这个更爽,可以引入各种库,当然可以对这些库的功能做测试了。

open(url, callback) {void}

Opens the url and loads it to the page. Once the page is loaded, the optional callback is called using WebPage#onLoadFinished, and also provides the page status to the function ('success' or 'fail').

Example:

page.open('http://www.google.com/', function(status) { console.log('Status: ' + status); // Do other things here... });

也是一个很实用的api,打开页面。

上面介绍了一部分的api,所有的api在https://github.com/ariya/phantomjs/wiki/API-Reference#wiki-webpage-url

虽然不多,但是真心牛逼。。。。。。。。。。。。。。

重头戏来了 文件api

// 文件遍历器 var system = require('system');//载入系统模块,这样就可以传参数了。参数用空格分割 if (system.args.length !== 2) {//判断参数个数,容错 console.log("Usage: phantomjs scandir.js DIRECTORY_TO_SCAN"); phantom.exit(1); } var scanDirectory = function (path) { //初始输入参数为目录 var fs = require('fs');//加载文件模块 if (fs.exists(path) && fs.isFile(path)) { console.log(path);//如果文件存在,则打印当前路径 } else if (fs.isDirectory(path)) {//如果这个是一个目录 fs.list(path).forEach(function (e) {//展开这个目录的文件列表,遍历并列举出来 if ( e !== "." && e !== ".." ) { //< Avoid loops   这里我不太懂,估计是为了怕死循环吧 scanDirectory(path + '/' + e); //迭代,判断每个path是不是文件 } }); } }; scanDirectory(system.args[1]); phantom.exit();

里面的api封装了nodejs的一些api,写起来更加好用了(尼玛至少不用写一堆堆的花括号回调了)

可以作为自动化工具来使用~

ps  dos 可以利用 >1.txt 把控制台信息输出到文件里~

你可能感兴趣的:(phantomjs学习笔记)