Skip to content

Latest commit

 

History

History
173 lines (151 loc) · 5.96 KB

1.Quickstart-快速入门.md

File metadata and controls

173 lines (151 loc) · 5.96 KB

快速入门

如果CasperJS已经在你的电脑上安装好,你就可以开始编写你的第一个脚本啦!你可以使用原生JavaScript(或PhantomJS2.0之前版本支持的 CoffeeScript)来编写脚本。

提示

如果你还不习惯使用JavaScript,请阅读这个FAQ条目

最简单的CasperJS脚本

打开你最爱的编辑器,创建一个名为sample.js的文件,写入以下代码:

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();

运行脚本(使用python):

$ casperjs sample.js

运行脚本(使用node):这里有关于node的详细信息

$ node casperjs.js sample.js

运行脚本(使用PhantomJS)

$ phantomjs casperjs.js sample.js

运行脚本(使用windows命令行)

C:\casperjs\bin> casperjs.exe sample.js

你应该得到如下的结果:

$ casperjs sample.js
CasperJS, a navigation scripting and testing utility for PhantomJS
PhantomJS: Headless WebKit with JavaScript API
我刚刚做了什么?
  1. 我们创建了一个新的Casper实例。
  2. 我们开始运行脚本,并打开了http://casperjs.org/。
  3. 当页面加载完毕后,我们请求打印出这个网页的标题(也就是<title>标签中的内容)。
  4. 我们打开了另一个链接,http://phantomjs.org/。
  5. 当页面加载完毕后,我们也请求打印出这个页面的标题。
  6. 结束整个进程。

我们来抓取Google吧

在下面的例子中,我们将连续向Google查询两个词语,分别是”casperjs“和”phantomjs“,然后将结果链接集合到数组中,并将结果输出到控制台。(友情提示如果你在中国的话访问Google是需要翻墙的)

打开你最爱的编辑器并将以下代码保存到文件googlelinks.js中:

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();
});

运行它:

$ 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

CoffeeScript版本

你也可以使用CoffeeScript语法编写CasperJS程序:

getLinks = ->
 links = document.querySelectorAll "h3.r a"
 Array::map.call links, (e) -> e.getAttribute "href"

links = []
casper = require('casper').create()

casper.start "http://google.fr/", ->
 # search for 'casperjs' from google form
 @fill "form[action='/search']", q: "casperjs", true

casper.then ->
 # aggregate results for the 'casperjs' search
 links = @evaluate getLinks
 # search for 'phantomjs' from google form
 @fill "form[action='/search']", q: "phantomjs", true

casper.then ->
 # concat results for the 'phantomjs' search
 links = links.concat @evaluate(getLinks)

casper.run ->
 # display results
 @echo links.length + " links found:"
 @echo(" - " + links.join("\n - ")).exit()

一个简单的测试程序

CasperJS同时也是一个测试框架,测试脚本与抓取脚本略有不同,尽管它们共享了大部分的API。

一个简单的测试脚本:

// hello-test.js
casper.test.begin("Hello, Test!", 1, function(test) {
  test.assert(true);
  test.done();
});

使用CasperJS的测试子命令来运行它:

$ 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.
提示

如你所见,你不需要在测试脚本中创建一个casper实例,因为预配置的实例已经可供你使用。 你可以在测试部分的文档中了解更多信息。