CasperJS 自动化web操作

CasperJS是一个开源的导航脚本处理和测试工具,基于PhantomJS(前端自动化测试工具)编写。CasperJS简化了完整的导航场景的过程定义,提供了用于完成常见任务的实用的高级函数、方法和语法。
CasperJS 的官方文档地址:http://casperjs.readthedocs.io/en/latest/#casperjs-documentation
本文大部分为翻译官方的文档

安装

  1. 需要先安装PhantomJS 19.1或者更新的版本 installation instructions for PhantomJS
  2. 需要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的选择器:

  • CSS3
  • XPath
    下面的例子都是基于这个HTML页面
<!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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • Swift版本点击这里欢迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh阅读 25,586评论 7 249
  • 图片发自简书App 一定会有未来未来一定会有更多朋友一定会有吃和穿未来一定会在某棵树上吊死未来一定会老去一定会忘记...
    高华栋阅读 245评论 8 12
  • 第一次 作为一名学生党,越学习,越觉得自己太菜。开发的生涯还很短,也总会遇到一些坑又或者只是自己比较菜,不断的走一...
    Hugh1029阅读 233评论 0 0
  • 作业1:你认为有10万+阅读潜质的标题 1:且看!平凡的人如何活的不平凡? 2:魔方时速,穿梭在天堂与地狱的人。 ...
    seaarea阅读 187评论 0 0