PhantomJS 网页截屏

本文介绍PhantomJS的安装步骤及使用方法,包括环境变量配置、基本脚本编写、参数传递方式、页面加载和截图等功能。适用于希望利用PhantomJS进行网页自动化操作的开发者。

一、安装

安装包下载地址:http://phantomjs.org/download.html,包括Windows,Mac OS,Linux版本,自行选择对应 版本下载解压即可(为方便使用,可自已为phantomjs设置环境变量),其中带有一个example文件夹,里面有很多已经写好的代码供使用。本文假设phantomjs已经安装好并已设置了环境变量。

二、使用

Hello, World!

新建一个包含下面两行脚本的文本文件:

1
2
console.log( 'Hello, world!' );
phantom.exit();

将文件另存为hello.js,然后执行它:

1
phantomjs hello.js

输出结果为:Hello, world!

第一行将会在终端打印出字符串,第二行phantom.exit将退出运行。
在该脚本中调用phantom.exit是非常重要的,否则 PhantomJS 将根本不会停止。

脚本参数 – Script Arguments

Phantomjs如何传递参数呢?如下所示 :

1
phantomjs examples/arguments.js foo bar baz

其中的foo, bar, baz就是要传递的参数,如何获取呢:

1
2
3
4
5
6
7
8
9
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();

它将输出 :

0: foo
1: bar
2: baz

页面加载 – Page Loading

通过创建一个网页对象,一个网页可以被加载,分析和渲染。

下面的脚本将示例页面对象最简单的用法,它加载 example.com 并且将它保存为一张图片,example.png

1
2
3
4
5
var  page = require( 'webpage' ).create();
page.open( 'http://example.com' , function  () {
     page.render( 'example.png' );
     phantom.exit();
});

由于它的这个特性,PhantomJS 网页截屏,截取一些内容的快照,比如将网页、SVG存成图片,PDF等,这个功能很牛X。

接下来的loadspeed.js脚本加载一个特殊的URL (不要忘了http协议) 并且计量加载该页面的时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var  page = require( 'webpage' ).create(),
     system = require( 'system' ),
     t, address;
 
if  (system.args.length === 1) {
     console.log( 'Usage: loadspeed.js <some URL>' );
     phantom.exit();
}
 
t = Date.now();
address = system.args[1];
page.open(address, function  (status) {
     if  (status !== 'success' ) {
         console.log( 'FAIL to load the address' );
     } else  {
         t = Date.now() - t;
         console.log( '<a title="Loading" href="http://www.woiweb.net/tag/loading">Loading</a> time '  + t + ' msec' );
     }
     phantom.exit();
});

转载于:https://www.cnblogs.com/shaojc85/p/3660040.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值