PhantomJS入门

PhantomJS是什么?

PhantomJS is a headless web browser scriptable with JavaScript. It runs on Windows, macOS, Linux, and FreeBSD.(PhantomJS 是一个可编写JS脚本的无头浏览器,可以运行在macOS,Linux,FreeBSD上)。这是PhantomJS官网上的介绍,简单来说,PhantomJS是一个没有图形用户界面(GUI)的浏览器,通常通过命令行来控制。

PhantomJS能做什么?

网页自动化测试

希望自动的登陆网站并做一些操作然后检查结果是否正常

网页监控

希望定期打开页面,检查网站是否能正常加载,加载结果是否符合预期。加载速度如何等。

网络爬虫

获取页面中使用js来下载和渲染信息,或者是获取链接处使用js来跳转后的真实地址。

网页截屏

可以打开一个网页并生成一个网页的截屏。

PhantomJS的几个入门DEMO

网页截屏

下面的脚本演示了打开一个URL,并生成该URL的图片保存在本地。

1
2
3
4
5
6
7
8
var page = require('webpage').create();
page.open('https://www.baidu.com', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('baidu.png');
}
phantom.exit();
});

网页监控

该脚本记录了某个URL下所有的请求和响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

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

if (system.args.length === 1) {
console.log('Usage: netlog.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];

page.onResourceRequested = function (req) {
console.log('requested: ' + JSON.stringify(req, undefined, 4));
};

page.onResourceReceived = function (res) {
console.log('received: ' + JSON.stringify(res, undefined, 4));
};

page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
phantom.exit();
});
}

DOM操作

如下脚本打开百度页面之后,返回了ID选择器所对应元素内部的文本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"use strict";
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
// page.settings.userAgent = 'SpecialAgent';
page.open('https://www.baidu.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementById('head').innerText;
});
console.log(ua);
}
phantom.exit();
});

还有哪些headless浏览器?

Firefox,Chrome,Microsoft Edge

参考

  1. PhantomJS - Scriptable Headless Browser

  2. 网络监控 | PhantomJS (kuryun.com)

  3. 无头浏览器ChromeDriver安装,java 使用 driver 网页截图_哈赛给的博客-CSDN博客

  4. 如何使用ChromeHeadLess 技术实现后台对前台页面截屏xsviglh的博客-CSDN博客_chrome headless 截图

显示评论