[译文]casperjs 的API-casper模块

Casper class:

可以通过这个模块的create()方法来获取这个模块的一个实例,这是最容易的:

var casper = require('casper').create();
我们也可以通过实例化主方法的方式获得一个自身的实例:
var casper = new require('casper').Casper();
提示:
如果扩展casper类,后面的章节会讲到
 
不管是casper构造函数还是create()方法,都接受一个参数选项,这个标准的javascript对象一样。
var casper = require('casper').create({
    verbose: true,
    logLevel: "debug"
});

Casper.options

一个 options对象能被传入casper构造函数,如下例:

var casper = require('casper').create({
    clientScripts:  [
        'includes/jquery.js',      // These two scripts will be injected in remote
        'includes/underscore.js'   // DOM on every request
    ],
    pageSettings: {
        loadImages:  false,        // The WebPage instance used by Casper will
        loadPlugins: false         // use these settings
    },
    logLevel: "info",              // Only "info" level messages will be logged
    verbose: true                  // log messages will be printed out to the console
});
你也能够在运行时中改变 options:
var casper = require('casper').create();
casper.options.waitTimeout = 1000;
 
所有可用的属性如下:
 
clientScripts

Type: Array

Default: []

一个本地script脚本文件路径的集合,它们能被加载到所有页面

exitOnError

Type: Boolean

Default: true

如果CasperJS的脚本在运行过程中出现一个uncaught error ,那么casperjs运行结束

httpStatusHandlers

Type: Object

Default: {}

一个javascript对象,他包含了一个获取到指定http状态的就触发执行的回调方法,使用方法已经包含在例子中了

logLevel

Type: String

Default: "error"

日志等级

onAlert

Type: Function

Default: null

当一个javascript 的alert()被触发时的回调方法

onDie

Type: Function

Default: null

当Casper#die() 被触发时的回调方法

onError

Type: Function

Default: null

当一个“error”等级的事件被触发时的回调方法

onLoadError

Type: Function

Default: null

请求的资源没有被load下来时被触发的回调方法

onPageInitialized

Type: Function

Default: null

页面已经被初始化后被触发的回调方法

onResourceReceived

Type: Function

Default: null

该方法替换了PhantomJS的WebPage#onResourceReceived()的回调,只要正确的casper实例作为第一个参数被传入

onResourceRequested

Type: Function

Default: null

该方法替换了PhantomJS的WebPage#onResourceRequested()的回调,只要正确的casper实例作为第一个参数被传入

onStepComplete

Type: Function

Default: null

当一个step方法已经执行完成后,这个方法被执行

onStepTimeout

Type: Function

Default: Function

当一个step方法在执行超时后,如果设置了这个方法,这个方法将被执行

默认情况下,脚本会退出并显示一个错误,如果是在test环境中,它将会增加一个失败到测试结果中。

onTimeout

Type: Function

Default: Function

当脚本在执行时,超过了option设置的timeout值后,如果设置了这个方法,这个方法将被执行

默认情况下,超时的脚本将会退出并显示错误,如果是在test环境中,它将会增加一个失败到测试结果中。

onWaitTimeout

Type: Function

Default: Function

当一个waitFor*方法在执行时,超过了设置的waitTimeout 值后,如果设置了这个方法,这个方法将被执行

默认情况下,超时的脚本将会退出并显示错误,如果是在test环境中,它将会增加一个失败到测试结果中。

page

Type: WebPage

Default: null

一个存在于PhantomJS的 webPage实例

pageSettings

Type: Object

Default: {}

PhantomJS的 webPage实例,可用的设置如下:

  • javascriptEnabled 定义了页面是否执行script脚本 (默认为true)
  • loadImages 定义了是否加载图片(默认为true)
  • loadPlugins 定义了是否加载 NPAPI 插件 (Flash, Silverlight, …)
  • localToRemoteUrlAccessEnabled 定义了本地资源是否可以上传(默认为 false)
  • userAgent 定义了页面请求服务器资源时的userAgent
  • userName 设置http认证的用户名
  • password 设置http认证的密码
  • XSSAuditingEnabled 定义是否能发起跨域请求(默认为 false)
remoteScripts

Type: Array

Default: []

新增于1.0版本

一个远程script脚本文件路径的集合,它们能被加载到所有页面

safeLogs

Type: Boolean

Default: true

新增于1.0版本

当这个属性设置为true,从 获得的密码信息将不被明文显示出来,它是默认为true,设置safelogs为false,密码会被明文显示(不推荐)

silentErrors

Type: Boolean

Default: false

When this option is enabled, caught step errors are not thrown (though related events are still emitted). Mostly used internally in a testing context.

当这个选项是可用的,会导致步骤错误不会被抛出,一般用户测试框架中

stepTimeout

Type: Number

Default: null

用毫秒计算的最大step超时时间,当设置以后,每个定义的step方法都将在超时时间到达以前执行完成,你可以定义onStepTimeout() 回调方法来捕获这种情况,默认情况下,这个脚本将会抛出一个错误信息并结束

timeout

Type: Number

Default: null

用毫秒计算的最大超时时间

verbose

Type: Boolean

Default: false

实时输出log信息

viewportSize

Type: Object

Default: null

窗口尺寸, eg. {width: 800, height: 600}

提示:

phantomjs默认的窗口尺寸为400*300, casperjs继承了这个尺寸

retryTimeout

Type: Number

Default: 100

重试时的默认延迟间隔时间,在 wait*系列的方法中生效

waitTimeout

Type: Number

Default: 5000

默认的等待超时时间,在 wait*系列的方法中生效

 

Casper prototype

back()

Signature: back()

Moves back a step in browser’s history:

从浏览器的历史记录回退一步

casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back();
casper.run(function() {
    console.log(this.getCurrentUrl()); // 'http://foo.bar/2'
});
也可以查看forward()
 
base64encode()

Signature: base64encode(String url [, String method, Object data])

Encodes a resource using the base64 algorithm synchronously using client-side XMLHttpRequest.

对客户端的XMLHttpRequest进行base64编码转换

注意:

我们不能使用window.btoa(),因为它在webkit版本的phantomjs中会导致失败

实例: 对 google logo 图片进行base64编码:

var base64logo = null;
casper.start('http://www.google.fr/', function() {
    base64logo = this.base64encode('http://www.google.fr/images/srpr/logo3w.png');
});

casper.run(function() {
    this.echo(base64logo).exit();
});
你也能将一个http post请求的内容进行编码
var base64contents = null;
casper.start('http://domain.tld/download.html', function() {
    base64contents = this.base64encode('http://domain.tld/', 'POST', {
        param1: 'foo',
        param2: 'bar'
    });
});

casper.run(function() {
    this.echo(base64contents).exit();
});
bypass()

Signature: bypass(Numbr nb)

新增于1.1版本

Bypasses a given number of defined navigation steps:

跳过指定数量的步骤

casper.start();
casper.then(function() {
    // This step will be executed
});
casper.then(function() {
    this.bypass(2);
});
casper.then(function() {
    // This test won't be executed
});
casper.then(function() {
    // Nor this one
});
casper.run();
click()

Signature: click(String selector)

对匹配表达式的元素执行一次点击,这个方法用两种方式进行尝试:

 

  1. 尝试触发一次Javascript 的 MouseEvent事件
  2. 如果先前的方法不行,则触发一次QtWebKit事件

实例:

casper.start('http://google.fr/');

casper.thenEvaluate(function(term) {
    document.querySelector('input[name="q"]').setAttribute('value', term);
    document.querySelector('form[name="f"]').submit();
}, 'CasperJS');

casper.then(function() {
    // Click on 1st result link
    this.click('h3.r a');
});

casper.then(function() {
    console.log('clicked ok, new location is ' + this.getCurrentUrl());
});

casper.run();
clickLabel()

Signature: clickLabel(String label[, String tag])

新增于0.6.1版本

Clicks on the first DOM element found containing label text. Optionaly ensures that the element node name is tag:

点击匹配到包含指定文本的第一个DOM元素,或者确保元素的节点名是一个标签

// My link is beautiful
casper.then(function() {
    this.clickLabel('My link is beautiful', 'a');
});

// 
casper.then(function() {
    this.clickLabel('But my button is sexier', 'button');
});
capture()

Signature: capture(String targetFilepath, [Object clipRect, Object imgOptions])

PhantomJS’ WebPage#render的替代方法. 增加 一个 clipRect 参数,他能够设置页面的大小

casper.start('http://www.google.fr/', function() {
    this.capture('google.png', {
        top: 100,
        left: 100,
        width: 500,
        height: 400
    });
});

casper.run();
新增于1.1版本

 imgOptions 对象允许指定两个选项:

  • format 用来设置图片格式,避免依靠文件名
  • quality 用来设置图片的质量,从 1到100

实例:

casper.start('http://foo', function() {
    this.capture('foo', undefined, {
        format: 'jpg',
        quality: 75
    });
});
captureBase64()

Signature: captureBase64(String format[, Mixed area])

新增于 0.6.5.

Computes the Base64 representation of a binary image capture of the current page, or an area within the page, in a given format.

截屏Base64编码的二进制图片,它可以根据给定的格式,截屏全部页面,也可以截屏页面的某个区域

支持这些图片格式:bmp, jpg, jpeg, png, ppm, tiff, xbm , xpm.

area选项可以用以下的形式:

  • String: area是一个  CSS3 表达式字符串, eg. div#plop form[name="form"] input[type="submit"]
  • clipRect: area 是一个clipRect 对象, eg. {"top":0,"left":0,"width":320,"height":200}
  • Object: area是一个表达式对象, eg. an XPath selector

实例:

casper.start('http://google.com', function() {
    // selector capture
    console.log(this.captureBase64('png', '#lga'));
    // clipRect capture
    console.log(this.captureBase64('png', {
        top: 0,
        left: 0,
        width: 320,
        height: 200
    }));
    // whole page capture
    console.log(this.captureBase64('png'));
});
casper.run();
captureSelector()

Signature: captureSelector(String targetFile, String selector [, Object imgOptions])

Captures the page area containing the provided selector and saves it to targetFile:

根据页面区域提供的表达式截取页面并且保存为一个目标文件

casper.start('http://www.weather.com/', function() {
    this.captureSelector('weather.png', '#wx-main');
});

casper.run();

新增于1.1版本

imgOptions对象允许指定两个参数

  • format 用来设置图片格式,避免依靠文件名
  • quality 用来设置图片的质量,从 1到100
clear()

Signature: clear()

新增于 0.6.5.

清楚当前页面的执行环境上下文,用于避免以前页面的dom仍然存在。

可以把他作为停止远程DOM环境下javascript执行的一种方法:

casper.start('http://www.google.fr/', function() {
    this.clear(); // javascript execution in this page has been stopped
});

casper.then(function() {
    // ...
});

casper.run();
debugHTML()

Signature: debugHTML([String selector, Boolean outer])

向控制台输出getHTML()的结果,它和getHTML()具有同样的参数。

debugPage()

Signature: debugPage()

Logs the textual contents of the current page directly to the standard output, for debugging purpose:

记录当前页面的文本并且输出到标准输出,主要用来调试

casper.start('http://www.google.fr/', function() {
    this.debugPage();
});

casper.run();
die()

Signature: die(String message[, int status])

Exits phantom with a logged error message and an optional exit status code:

当记录到一个error时,退出phantom,并且设置退出状态码

casper.start('http://www.google.fr/', function() {
    this.die("Fail.", 1);
});

casper.run();
download()

Signature: download(String url, String target[, String method, Object data])

Saves a remote resource onto the filesystem. You can optionally set the HTTP method using the method argument, and pass request arguments through the data object (see base64encode()):

保存一个远程资源文件到文件系统,你可以设置可选参数,使用method设置http请求方法,使用data设置请求参数

casper.start('http://www.google.fr/', function() {
    var url = 'http://www.google.fr/intl/fr/about/corporate/company/';
    this.download(url, 'google_company.html');
});

casper.run(function() {
    this.echo('Done.').exit();
});
注意:
如果你在下载文件时碰到一些麻烦,尝试不使用web security.
 
each()

Signature: each(Array array, Function fn)

遍历数组里的元素,去执行一个回调:

var links = [
    'http://google.com/',
    'http://yahoo.com/',
    'http://bing.com/'
];

casper.start().each(links, function(self, link) {
    self.thenOpen(link, function() {
        this.echo(this.getTitle());
    });
});

casper.run();
提示:
googlematch.js是一个使用它的例子
chThen()

Signature: eachThen(Array array, Function then)

New in version 1.1.

Iterates over provided array items and adds a step to the stack with current data attached to it:

遍历数组里的元素,增加一个步骤,用元素去处理它:

casper.start().eachThen([1, 2, 3], function(response) {
    this.echo(response.data);
}).run();
这是一个打开URL的例子:
var casper = require('casper').create();
var urls = ['http://google.com/', 'http://yahoo.com/'];

casper.start().eachThen(urls, function(response) {
  this.thenOpen(response.data, function(response) {
    console.log('Opened', response.url);
  });
});

casper.run();
提示:
当前的元素将被存储在response.data属性里
 
echo()

Signature: echo(String message[, String style])

Prints something to stdout, optionally with some fancy color (see the colorizer module for more information):

打印一些东西到标准输出,可选参数可以让你设置你想要的颜色

casper.start('http://www.google.fr/', function() {
    this.echo('Page title is: ' + this.evaluate(function() {
        return document.title;
    }), 'INFO'); // Will be printed in green on the console
});

casper.run();
 
evaluate()

Signature: evaluate(Function fn[, arg1[, arg2[, …]]])

基于PhantomJS’ WebPage#evaluate ,在当前页面的DOM环境下执行javascript语句:

casper.evaluate(function(username, password) {
    document.querySelector('#username').value = username;
    document.querySelector('#password').value = password;
    document.querySelector('#submit').click();
}, 'sheldon.cooper', 'b4z1ng4');
提示:
如果是填充或者提交表单,最好使用fill()方法
 

注意:在1.0版本以前,这种方式传递的参数使用一个被保存来用于其他目的的对象,所以它可能在某些情况系不会工作,所以我们鼓励你使用上述方法。

 
理解 evaluate():
这种方法背后的概念可能是在capserjs中最难理解的,作为一个提示,可以把evaluate()方法想象成连接CasperJS 环境和一个打开页面的一扇门,每当你使用evaluate(),你就进入了浏览器控制台,并且进入页面执行代码。
这是一个示意图用来描述两者之间的关系

[译文]casperjs 的API-casper模块_第1张图片


evaluateOrDie()

Signature: evaluateOrDie(Function fn[, String message])

Evaluates an expression within the current page DOM and die() if it returns anything but true:

在当前页面的dom环境中执行一个语句,如果他返回的是不为true的任何东西,都会执行die()

    this.evaluateOrDie(function() {
        return /logged in/.match(document.title);
    }, 'not authenticated');
});

casper.run();
exit()

Signature: exit([int status])

Exits PhantomJS with an optional exit status code.

退出phantomjs,并且返回一个退出状态码

exists()

Signature: exists(String selector)

Checks if any element within remote DOM matches the provided selector:

检查是否有DOM元素匹配提供的表达式

casper.start('http://foo.bar/home', function() {
    if (this.exists('#my_super_id')) {
        this.echo('found #my_super_id', 'INFO');
    } else {
        this.echo('#my_super_id not found', 'ERROR');
    }
});

casper.run();
fetchText()

Signature: fetchText(String selector)

Retrieves text contents matching a given selector expression. If you provide one matching more than one element, their textual contents will be concatenated:

获取一个给定的选择器表达式匹配的文本内容,如果他们匹配了不止一个元素,他们的文本内容将被连接起来

casper.start('http://google.com/search?q=foo', function() {
    this.echo(this.fetchText('h3'));
}).run();
forward()

Signature: forward()

Moves a step forward in browser’s history:

从浏览器的历史记录向前一步

casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back();    // http://foo.bar/2
casper.back();    // http://foo.bar/1
casper.forward(); // http://foo.bar/2
casper.run();
也可以查看back()
 
log()

Signature: log(String message[, String level, String space])

记录一条消息在一个可选的空间,一个可选的级别, 可选的级别是 debug, info, warningerror. space是一个可以设置过滤你的日志的命名空间。默认情况下, Casper 日志在两个不同的空间: phantomremote, 用来区分它是发生在PhantomJS环境还是远程环境:

casper.start('http://www.google.fr/', function() {
    this.log("I'm logging an error", "error");
});

casper.run();
 
fill()

Signature: fill(String selector, Object values[, Boolean submit])

Fills the fields of a form with given values and optionally submits it. Fields are referenced by their name attribute.

用给定的值填充表单的内容并且提交它,使用它们的name属性

1.1版本变化:可以使用css3或者xpath来替代,可以使用fillSelectors() 和 fillXPath() 方法.

html表单的例子:

Mr Mrs Receive a copy
一个提交表单的脚本:
casper.start('http://some.tld/contact.form', function() {
    this.fill('form#contact-form', {
        'subject':    'I am watching you',
        'content':    'So be careful.',
        'civility':   'Mr',
        'name':       'Chuck Norris',
        'email':      '[email protected]',
        'cc':         true,
        'attachment': '/Users/chuck/roundhousekick.doc'
    }, true);
});

casper.then(function() {
    this.evaluateOrDie(function() {
        return /message sent/.test(document.body.innerText);
    }, 'sending message failed');
});

casper.run(function() {
    this.echo('message sent').exit();
});
 fill() 方法 支持 input的单选项. 如果是多行选择,采用列表的方式支持:
一个提交多行选项表单的实例:
casper.then(function() {
   this.fill('form#contact-form', {
       'categories': ['0', '1'] // Friends and Family
   });
});

注意:

  1. fill()方法不能使用xpath选择器去填充表单;phantomjs只允许使用css3选择器使用uploadFile()方法,因此,上传文件时,这种方法不生效
  2. 请不要使用casperjs或者phantomjs去发送垃圾邮件
fillSelectors()

Signature: fillSelectors(String selector, Object values[, Boolean submit])

新增于1.1版本

用给定的值填充表单的内容并且提交它,使用CSS3 选择器:

casper.start('http://some.tld/contact.form', function() {
    this.fillSelectors('form#contact-form', {
        'input[name="subject"]':    'I am watching you',
        'input[name="content"]':    'So be careful.',
        'input[name="civility"]':   'Mr',
        'input[name="name"]':       'Chuck Norris',
        'input[name="email"]':      '[email protected]',
        'input[name="cc"]':         true,
        'input[name="attachment"]': '/Users/chuck/roundhousekick.doc'
    }, true);
});
fillXPath()

Signature: fillXPath(String selector, Object values[, Boolean submit])

New in version 1.1.

Fills form fields with given values and optionally submits it. While the form element is always referenced by a CSS3 selector, fields are referenced by XPath selectors:

用给定的值填充表单的内容并且提交它,这时候form元素总是使用css3选择器,而fields选择xpath选择器

casper.start('http://some.tld/contact.form', function() {
    this.fillXPath('form#contact-form', {
        '//input[@name="subject"]':    'I am watching you',
        '//input[@name="content"]':    'So be careful.',
        '//input[@name="civility"]':   'Mr',
        '//input[@name="name"]':       'Chuck Norris',
        '//input[@name="email"]':      '[email protected]',
        '//input[@name="cc"]':         true,
    }, true);
});

注意:fillXPath()方法不能使用xpath填充字段,PhantomJS在uploadFile()时只能使用css3选择器,这是他的限制

 
getCurrentUrl()

Signature: getCurrentUrl()

Retrieves current page URL. Note that the url will be url-decoded:

获得当前页面的URL,注意这个URL是已经解码过的

casper.start('http://www.google.fr/', function() {
    this.echo(this.getCurrentUrl()); // "http://www.google.fr/"
});

casper.run();
getElementAttribute()

Signature: getElementAttribute(String selector, String attribute)

新增于1.0版本

Retrieves the value of an attribute on the first element matching the provided selector:

获取选择器匹配的第一个元素的属性值

var casper = require('casper').create();

casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google"
});

casper.run();
 
getElementsAttribute()

Signature: getElementsAttribute(String selector, String attribute)

New in version 1.1.

获取选择器匹配的所有元素的属性值

var casper = require('casper').create();

casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementsAttribute('div[title="Google"]', 'title')); // "['Google']"
});

casper.run();
getElementBounds()

Signature: getElementBounds(String selector)

获取选择器匹配的元素的区域

它返回一个对象,包括以下键:top, left, widthheight,如果没有匹配到元素,则返回null

var casper = require('casper').create();

casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementBounds('div[title="Google"]'));
});

casper.run();
将会得到以下输出:
{
    "height": 95,
    "left": 352,
    "top": 16,
    "width": 275
}
getElementsBounds()

Signature: getElementsBounds(String selector)

新增于1.0版本

获取选择器匹配的所有元素的区域信息的数组

它返回一个对象数组,对象包括以下四个键:top, left, widthheight

getElementInfo()

Signature: getElementInfo(String selector)

New in version 1.0.

Retrieves information about the first element matching the provided selector:

获取选择器匹配的第一个元素的信息

casper.start('http://google.fr/', function() {
    require('utils').dump(this.getElementInfo('#hplogo'));
});
得到以下结果:
{
    "attributes": {
        "align": "left",
        "dir": "ltr",
        "id": "hplogo",
        "onload": "window.lol&&lol()",
        "style": "height:110px;width:276px;background:url(/images/srpr/logo1w.png) no-repeat",
        "title": "Google"
    },
    "height": 110,
    "html": "
France
", "nodeName": "div", "tag": "
France
", "text": "France\n", "visible": true, "width": 276, "x": 62, "y": 76 }
提示:
这个方法返回的不是一个dom对象,它只是对象的一个描述,因为casper环境里是不能直接获取页面里的对象的
 
getElementsInfo()

Signature: getElementsInfo(String selector)

New in version 1.1.

获取选择器匹配的所有元素的信息

casper.start('http://google.fr/', function() {
    require('utils').dump(this.getElementsInfo('#hplogo'));
});
得到以下结果:
[
    {
        "attributes": {
            "align": "left",
            "dir": "ltr",
            "id": "hplogo",
            "onload": "window.lol&&lol()",
            "style": "height:110px;width:276px;background:url(/images/srpr/logo1w.png) no-repeat",
            "title": "Google"
        },
        "height": 110,
        "html": "
France
", "nodeName": "div", "tag": "
France
", "text": "France\n", "visible": true, "width": 276, "x": 62, "y": 76 } ]
这个方法返回的不是一个nodelist,它只是对象的列表的一个描述,因为casper环境里是不能直接获取页面里的对象的
 
getFormValues()

Signature: getFormValues(String selector)

新增于1.0版本

获取一个给定的表单的所有字段值:

casper.start('http://www.google.fr/', function() {
    this.fill('form', {q: 'plop'}, false);
    this.echo(this.getFormValues('form').q); // 'plop'
});

casper.run();
getGlobal()

Signature: getGlobal(String name)

通过名称,获取远程DOM环境下的一个全局变量的值,基本上,getGlobal('foo')意味着将从页面获得window.foo的值:

casper.start('http://www.google.fr/', function() {
    this.echo(this.getGlobal('innerWidth')); // 1024
});

casper.run();
getHTML()

Signature: getHTML([String selector, Boolean outer])

新增于1.0版本

获取当前页面的HTML代码,默认情况下,它会输出整个页面的html文本

casper.start('http://www.google.fr/', function() {
    this.echo(this.getHTML());
});

casper.run();
The getHTML() method can also dump HTML contents matching a given selector; for example with this HTML code:
getHTML()方法能得到给定的选择器匹配的元素的HTML文本;以下是HTML代码的实例:

    
        

Plop

你可以这样取得它的文本:
casper.start('http://www.site.tld/', function() {
    this.echo(this.getHTML('h1#foobar')); // => 'Plop'
});
outer参数允许你得到html格式的文本输出:
casper.start('http://www.site.tld/', function() {
    this.echo(this.getHTML('h1#foobar', true)); // => '

Plop

' });
getPageContent()

Signature: getPageContent()

新增于1.0版本

取得当前页面的文本,用其他文档类型来处理它:

var casper = require('casper').create();

casper.start().then(function() {
    this.open('http://search.twitter.com/search.json?q=casperjs', {
        method: 'get',
        headers: {
            'Accept': 'application/json'
        }
    });
});

casper.run(function() {
    require('utils').dump(JSON.parse(this.getPageContent()));
    this.exit();
});
getTitle()

Signature: getTitle()

获取当前页面的标题

casper.start('http://www.google.fr/', function() {
    this.echo(this.getTitle()); // "Google"
});

casper.run();
mouseEvent()

Signature: mouseEvent(String type, String selector)

新增于0.69版本

Triggers a mouse event on the first element found matching the provided selector.

对选择器匹配的第一个元素执行一个鼠标事件

支持的鼠标事件有mouseup, mousedown, click, mousemove, mouseovermouseout:

casper.start('http://www.google.fr/', function() {
    this.mouseEvent('click', 'h2 a');
});

casper.run();
open()

Signature: open(String location, Object Settings)

执行一个http请求打开一个给定的链接,你能够发起GET, POST, PUT, DELETEHEAD 请求

标准的get请求的实例:

casper.start();

casper.open('http://www.google.com/').then(function() {
    this.echo('GOT it.');
});

casper.run();

标准的POST请求的实例:

casper.start();

casper.open('http://some.testserver.com/post.php', {
    method: 'post',
    data:   {
        'title': 'Plop',
        'body':  'Wow.'
    }
});

casper.then(function() {
    this.echo('POSTED it.');
});

casper.run();
通过自定义参数的数组:
casper.open('http://some.testserver.com/post.php', {
       method: 'post',
       data: {
            'standard_param': 'foo',
            'nested_param[]': [       // please note the use of square brackets!
                'Something',
                'Something else'
            ]
       }
});
新增于1.0版本
你也可以增加公共的请求头,通过headers 选项:
casper.open('http://some.testserver.com/post.php', {
    method: 'post',
    data:   {
        'title': 'Plop',
        'body':  'Wow.'
    },
    headers: {
        'Accept-Language': 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3'
    }
});
reload()

Signature: reload([Function then])

新增于1.0版本

刷新当前页面的请求

casper.start('http://google.com', function() {
    this.echo("loaded");
    this.reload(function() {
        this.echo("loaded again");
    });
});

casper.run();
repeat()

Signature: repeat(int times, Function then)

针对当前的步骤,重复执行指定的次数

casper.start().repeat(3, function() {
    this.echo("Badger");
});

casper.run();
 
resourceExists()

Signature: resourceExists(String|Function|RegExp test)

检查资源是否已被加载,你可以将方法,字符串,正则表达式作为参数来执行测试:

casper.start('http://www.google.com/', function() {
    if (this.resourceExists('logo3w.png')) {
        this.echo('Google logo loaded');
    } else {
        this.echo('Google logo not loaded', 'ERROR');
    }
});

casper.run();
提示:
如果你想等待资源被加载,请使用waitForResource()方法。
 
run()

Signature: run(fn onComplete[, int time])

运行整个测试步骤,并且在执行完成后执行一个回调。很显然,这是一个强制执行casper测试的方法。

 

代码不会运行:

casper.start('http://foo.bar/home', function() {
    // ...
});

// hey, it's missing .run() here!
这样就会运行:
casper.start('http://foo.bar/home', function() {
    // ...
});

casper.run();
Casper.run() 也能接受一个onComplete回调,你可以考虑作为一个自定义的最后一步时要执行的所有其他的步骤被执行,不要忘记执行exit(),如果你执行回调。
casper.start('http://foo.bar/home', function() {
    // ...
});

casper.then(function() {
    // ...
});

casper.run(function() {
    this.echo('So the whole suite ended.');
    this.exit(); // <--- don't forget me!
});
Binding a callback to complete.error will trigger when the onComplete callback fails.
绑定一个回调到complete.error,当onComplete或调失败时触发
 
scrollTo()

Signature: scrollTo(Number x, Number y)

新增于1.1-beat3版本

滚动当前文档到根据x,y定义的指定的坐标系:

casper.start('http://foo.bar/home', function() {
    this.scrollTo(500, 300);
});
提示:
这个操作是同步的
 
scrollToBottom()

Signature: scrollToBottom()

新增于 1.1-beta3版本

滚动到当前文档的底部:

casper.start('http://foo.bar/home', function() {
    this.scrollToBottom();
});
提示:
这个操作是同步的
 
sendKeys()

Signature: sendKeys(Selector selector, String keys[, Object options])

新增于1.0版本

对选定的元素发送本地键盘事件:
casper.then(function() {
    this.sendKeys('form.contact input#name', 'Duke');
    this.sendKeys('form.contact textarea#message', "Damn, I'm looking good.");
    this.click('form.contact input[type="submit"]');
});
新增于1.1版本
目前支持sendkeys()方法的html元素有,