CasperJS 自动化web操作
CasperJS是一个开源的导航脚本处理和测试工具,基于PhantomJS(前端自动化测试工具)编写。CasperJS简化了完整的导航场景的过程定义,提供了用于完成常见任务的实用的高级函数、方法和语法。
CasperJS 的官方文档地址:http://casperjs.readthedocs.io/en/latest/#casperjs-documentation
本文大部分为翻译官方的文档
安装
- 需要先安装PhantomJS 19.1或者更新的版本 installation instructions for PhantomJS
- 需要Python 2.6 或者更新的版本
windows下载文件为 https://github.com/casperjs/casperjs/zipball/master
其他OS的安装请参考官方文档: http://casperjs.readthedocs.io/en/latest/installation.html
快速开始
一个简单的例子
var casper = require('casper').create();
casper.start('http://casperjs.org/', function() {
this.echo(this.getTitle());
});
casper.thenOpen('http://phantomjs.org', function() {
this.echo(this.getTitle());
});
casper.run();
Run it (with python):
$ casperjs sample.js
Run it (with node):
$ node casperjs.js sample.js
Run it (with PhantomJS):
$ phantomjs casperjs.js sample.js
Run it (on windows):
C:\casperjs\bin> casperjs.exe sample.js
You should get something like this:
$ casperjs sample.js
CasperJS, a navigation scripting and testing utility for PhantomJS
PhantomJS: Headless WebKit with JavaScript API
一个复杂的例子
var links = [];
var casper = require('casper').create();
function getLinks() {
var links = document.querySelectorAll('h3.r a');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('href');
});
}
casper.start('http://google.fr/', function() {
// Wait for the page to be loaded
this.waitForSelector('form[action="/search"]');
});
casper.then(function() {
// search for 'casperjs' from google form
this.fill('form[action="/search"]', { q: 'casperjs' }, true);
});
casper.then(function() {
// aggregate results for the 'casperjs' search
links = this.evaluate(getLinks);
// now search for 'phantomjs' by filling the form again
this.fill('form[action="/search"]', { q: 'phantomjs' }, true);
});
casper.then(function() {
// aggregate results for the 'phantomjs' search
links = links.concat(this.evaluate(getLinks));
});
casper.run(function() {
// echo results in some pretty fashion
this.echo(links.length + ' links found:');
this.echo(' - ' + links.join('\n - ')).exit();
});
Run it:
$ casperjs googlelinks.js
20 links found:
- https://github.com/casperjs/casperjs
- https://github.com/casperjs/casperjs/issues/2
- https://github.com/casperjs/casperjs/tree/master/samples
- https://github.com/casperjs/casperjs/commits/master/
- http://www.facebook.com/people/Casper-Js/100000337260665
- http://www.facebook.com/public/Casper-Js
- http://hashtags.org/tag/CasperJS/
- http://www.zerotohundred.com/newforums/members/casper-js.html
- http://www.yellowpages.com/casper-wy/j-s-enterprises
- http://local.trib.com/casper+wy/j+s+chinese+restaurant.zq.html
- http://www.phantomjs.org/
- http://code.google.com/p/phantomjs/
- http://code.google.com/p/phantomjs/wiki/QuickStart
- http://svay.com/blog/index/post/2011/08/31/Paris-JS-10-%3A-Introduction-%C3%A0-PhantomJS
- https://github.com/ariya/phantomjs
- http://dailyjs.com/2011/01/28/phantoms/
- http://css.dzone.com/articles/phantom-js-alternative
- http://pilvee.com/blog/tag/phantom-js/
- http://ariya.blogspot.com/2011/01/phantomjs-minimalistic-headless-webkit.html
- http://www.readwriteweb.com/hack/2011/03/phantomjs-the-power-of-webkit.php
一个简单的测试例子
// hello-test.js
casper.test.begin("Hello, Test!", 1, function(test) {
test.assert(true);
test.done();
});
结果
$ casperjs test hello-test.js
Test file: hello-test.js
# Hello, Test!
PASS Subject is strictly true
PASS 1 test executed in 0.023s, 1 passed, 0 failed, 0 dubious, 0 skipped.
Logging
CasperJS 使用 casper.log() 函数用来log,有下面四种log level。 和python 中的logging 很类似
- debug
- info
- warning
- error
一个简单的例子:
var casper = require('casper').create();
casper.log('plop', 'debug');
casper.log('plip', 'warning');
默认情况下这些log 是不会打印出来的,如果需要,你必须打开verbose
这个选项, 而且默认情况下loglevel 是error, 你可以通过logLevel
来进行更改, 如下:
var casper = require('casper').create({
verbose: true
logLevel: 'debug'
});
选择器
CasperJS支持两种操作DOM的选择器:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My page</title>
</head>
<body>
<h1 class="page-title">Hello</h1>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<footer><p>©2012 myself</p></footer>
</body>
</html>
CSS3
下面这个例子是用来检查<h1 class="page-title">
的元素是否存在
var casper = require('casper').create();
casper.start('http://domain.tld/page.html', function() {
if (this.exists('h1.page-title')) {
this.echo('the heading exists');
}
});
casper.run();
CSS3 选择器的文章: http://www.w3school.com.cn/cssref/css_selectors.asp
Xpath
上面的例子一样可以用XPath来实现
casper.start('http://domain.tld/page.html', function() {
this.test.assertExists({
type: 'xpath',
path: '//*[@class="plop"]'
}, 'the element exists');
});
为了更方便的使用XPath, 你可以使用selectXPath
帮助
var x = require('casper').selectXPath;
casper.start('http://domain.tld/page.html', function() {
this.test.assertExists(x('//*[@id="plop"]'), 'the element exists');
});
Trip
判断页面是否正确返回或者渲染完毕,可以用wait函数
casper.thenOpen(url, function initialAppearance() {
casper.waitForText('Text in deep part of page or modal');
});
有篇讲 CasperJS做UT的文章很好,要做UT的可以去看看:
http://www.oschina.net/translate/simpler-ui-testing-with-casperjs
API 文档速查,截屏,后退什么的都在这里 http://casperjs.readthedocs.io/en/latest/#casperjs-documentation