phantomjs的使用

PhantomJS是一个无界面的,可脚本编程的WebKit浏览器引擎。它原生支持多种web 标准:DOM 操作,CSS选择器,JSON,Canvas 以及SVG,同时也提供了处理文件I/O的操作,从而使你可以向操作系统读写文件等。PhantomJS的用处可谓非常广泛,诸如网络监测、网页截屏、无需浏览器的 Web 测试、页面访问自动化等。

1.安装

phantomjs是完全开源的软件,可以直接下载源码编译后安装,也可以直接下载官网上编译好的文件安装。

各平台下的安装文件包地址:

windows
https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip

Mac os
https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip

Linux
https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2

下载安装包完毕后,直接解压即可。安装完成之后命令行输入
phantomjs -v 后如果出现版本号即为安装成功。

2.常用的内置对象

1.system:获得系统操作对象,包括命令行参数、phantomjs系统设置等信息

var system=require('system');

2.webpage:获取操作dom或web网页的对象,通过它可以打开网页、接收网页内容、request、response参数,其为最核心对象。提供了一套可以访问和操作web文档的核心方法,包括操作DOM、事件捕获、用户事件模拟等等。

var page = require('webpage');

3.fs:获取文件系统对象,通过它可以操作操作系统的文件操作,包括read、write、move、copy、delete等。

var fs = require('fs'); 

4.webserver:可以启动一个web服务。目前有10个并发请求的限制;任何其他请求都将排队等候。

var webserver = require('webserver');

3.常用API

1.通过page对象打开url链接,并可以回调其声明的回调函数,其回调发生的时机为该URL被彻底打开完毕,即该URL所引发的请求项被全部加载完,但ajax请求是与它的加载完成与否没有关系
page.open(url,function (status) {})
2.当page.open调用时,回首先执行该函数,在此可以预置一些参数或函数,用于后边的回调函数中
page.onLoadStarted = function() {}
3.page的所要加载的资源在加载过程中,出现了各种失败,则在此回调处理
page.onResourceError = function(resourceError) {}
4.page的所要加载的资源在发起请求时,都可以回调该函数
page.onResourceRequested = function(requestData, networkRequest) {}
5.page的所要加载的资源在加载过程中,每加载一个相关资源,都会在此先做出响应,它相当于http头部分, 其核心回调对象为response,可以在此获取本次请求的cookies、userAgent等
page.onResourceReceived = function(response) {}
6.欲在执行web网页时,打印一些输出信息到控制台,则可以在此回调显示。
page.onConsoleMessage = function (msg) {}
7.phantomjs是没有界面的,所以对alert也是无法直接弹出的,故phantomjs以该函数回调在page在执行过程中的alert事件
page.onAlert = function(msg) {}
8.当page.open中的url,它自己(不包括所引起的其它的加载资源)出现了异常,如404、no route to web site等,都会在此回调显示。
page.onError = function(msg, trace) {}
9.当page.open打开的url或是该url在打开过程中基于该URL进行了跳转,则可在此函数中回调。
page.onUrlChanged = function(targetUrl) {}
10.当page.open的目标URL被真正打开后,会在调用open的回调函数前调用该函数,在此可以进行内部的翻页等操作
page.onLoadFinished = function(status){}
11.在所加载的web page内部执行该函数,像翻页、点击、滑动等,均可在此中执行
page.evaluate(function(){})
12.将当前page的现状渲染成图片,输出到指定的文件中去。
page.render("")

4.例子

1.输出内容。新建hello.js。

"use strict";
console.log('Hello, world!');
phantom.exit();

命令行输入phantomjs hello.js。程序输出了 Hello,world!程序第三句话终止phantom 的执行。

2.获取输入的参数。新建arguments.js.

"use strict";
var system = require('system');
if (system.args.length === 1) {
    console.log('Try to pass some args when invoking this script!');
} else {
    system.args.forEach(function (arg, i) {
            console.log(i + ': ' + arg);
    });
}
phantom.exit();

命令行输入phantomjs arguments.js https://www.baidu.com 20180106 jie
输出结果:

0: phantomjs/arguments.js
1: https://www.baidu.com
2: 20180106
3: jie

其中第一个值是当前js文件的路径

3.页面加载,并返回页面标题

"use strict";
phantom.outputEncoding="utf-8";
var page = require('webpage').create();
page.open("http://blog.csdn.net", function(status) {
        var title = page.evaluate(function() {
        return document.title;
    });
    console.log('Page title is ' + title);
    phantom.exit();
});

返回的结果:

Page title is CSDN首页-全球最大中文IT社区

4.创建web服务

var webserver = require('webserver');
var server = webserver.create();
var service = server.listen('127.0.0.1:9999', function(request, response) {
  response.statusCode = 200;
  response.write('<html><body>Hello!</body></html>');
  response.close();
});

5.设置代理

"use strict";
var page = require('webpage').create(),
    system = require('system'),
    host, port, address;

if (system.args.length < 4) {
    console.log('Usage: openurlwithproxy.js <proxyHost> <proxyPort> <URL>');
    phantom.exit(1);
} else {
    host = system.args[1];
    port = system.args[2];
    address = system.args[3];
    phantom.setProxy(host, port, 'manual', '', '');
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('FAIL to load the address "' +
                address + '" using proxy "' + host + ':' + port + '"');
        } else {
            console.log('Page title is ' + page.evaluate(function () {
                return document.title;
            }));
        }
        phantom.exit();
    });
}
原文地址:https://www.cnblogs.com/ITer-jack/p/8231002.html