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,從<input type=”password”> 獲得的密碼信息將不被明文顯示出來,它是默認為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)
對匹配表達式的元素執行一次點擊,這個方法用兩種方式進行嘗試:
- 嘗試觸發一次Javascript 的 MouseEvent事件
- 如果先前的方法不行,則觸發一次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元素,或者確保元素的節點名是一個標簽
// <a href="...">My link is beautiful</a>
casper.then(function() {
this.clickLabel('My link is beautiful', 'a');
});
// <button type="submit">But my button is sexier</button>
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(),你就進入了瀏覽器控制台,並且進入頁面執行代碼。
這是一個示意圖用來描述兩者之間的關系

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, warning 和 error. space是一個可以設置過濾你的日志的命名空間。默認情況下, Casper 日志在兩個不同的空間: phantom 和 remote, 用來區分它是發生在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表單的例子:
<form action="/contact" id="contact-form" enctype="multipart/form-data">
<input type="text" name="subject"/>
<textearea name="content"></textearea>
<input type="radio" name="civility" value="Mr"/> Mr
<input type="radio" name="civility" value="Mrs"/> Mrs
<input type="text" name="name"/>
<input type="email" name="email"/>
<input type="file" name="attachment"/>
<input type="checkbox" name="cc"/> Receive a copy
<input type="submit"/>
</form>
一個提交表單的腳本:
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': 'chuck@norris.com',
'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的單選項. 如果是多行選擇,采用列表的方式支持:
<form action="/contact" id="contact-form" enctype="multipart/form-data">
<select multiple name="category">
<option value="0">Friends</option>
<option value="1">Family</option>
<option value="2">Acquitances</option>
<option value="3">Colleagues</option>
</select>
</form>
一個提交多行選項表單的實例:
casper.then(function() {
this.fill('form#contact-form', {
'categories': ['0', '1'] // Friends and Family
});
});
注意:
- fill()方法不能使用xpath選擇器去填充表單;phantomjs只允許使用css3選擇器使用uploadFile()方法,因此,上傳文件時,這種方法不生效
- 請不要使用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"]': 'chuck@norris.com',
'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"]': 'chuck@norris.com',
'//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, width 和 height,如果沒有匹配到元素,則返回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, width 和 height
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": "<div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div>",
"nodeName": "div",
"tag": "<div dir=\"ltr\" title=\"Google\" align=\"left\" id=\"hplogo\" onload=\"window.lol&&lol()\" style=\"height:110px;width:276px;background:url(/images/srpr/logo1w.png) no-repeat\"><div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div></div>",
"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": "<div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div>",
"nodeName": "div",
"tag": "<div dir=\"ltr\" title=\"Google\" align=\"left\" id=\"hplogo\" onload=\"window.lol&&lol()\" style=\"height:110px;width:276px;background:url(/images/srpr/logo1w.png) no-repeat\"><div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div></div>",
"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代碼的實例:
<html>
<body>
<h1 id="foobar">Plop</h1>
</body>
</html>
你可以這樣取得它的文本:
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)); // => '<h1 id="foobar">Plop</h1>'
});
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, mouseover 和 mouseout:
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, DELETE 和 HEAD 請求
標准的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元素有<input>, <textarea>,包括其他有contenteditable="true"屬性的html元素
Options
-
(Boolean) reset:
新增於1.1-beta3版本
當設置為 true, 這個屬性首先清空當前的元素值.默認情況下,它設置為 false,並且 sendKeys() 將通過追加的方式修改對應的值.
-
(Boolean) keepFocus:
sendKeys() 默認情況下會移除焦點,它將會自動的關閉窗口. 如果你想保持焦點,使用keepFocus 選項.例如, 如果你使用 jQuery-UI, 你能夠在你能夠在:
casper.then(function() { this.sendKeys('form.contact input#name', 'action', {keepFocus: true}); this.click('form.contact ul.ui-autocomplete li.ui-menu-item:first- child a'); }); -
(String) modifiers:
sendKeys()接受一個modifiers 去支持關鍵詞修飾語. 這個選項是一個關鍵詞修飾語的字符串, separated by the + character::
casper.then(function() { this.sendKeys('document', 's', {modifiers: 'ctrl+alt+shift'}); });可用的修飾語:
- ctrl
- alt
- shift
- meta
- keypad
setHttpAuth()
Signature: setHttpAuth(String username, String password)
設置 HTTP_AUTH_USER 和 HTTP_AUTH_PW 值, 這是為 HTTP 協議的認證體系設置的:
casper.start();
casper.setHttpAuth('sheldon.cooper', 'b4z1ng4');
casper.thenOpen('http://password-protected.domain.tld/', function() {
this.echo("I'm in. Bazinga.");
})
casper.run();
你也可以直接通過URL來打開:
var url = 'http://sheldon.cooper:b4z1ng4@password-protected.domain.tld/';
casper.start(url, function() {
this.echo("I'm in. Bazinga.");
})
casper.run();
start()
Signature: start(String url[, Function then])
配置開始casper,然后打開URL和通過then參數增加操作步驟:
casper.start('http://google.fr/', function() {
this.echo("I'm loaded.");
});
casper.run();
另外:
casper.start('http://google.fr/');
casper.then(function() {
this.echo("I'm loaded.");
});
casper.run();
再舉例:
casper.start('http://google.fr/');
casper.then(function() {
casper.echo("I'm loaded.");
});
casper.run();
上面都是不同的風格。
提示:
你必須調用start()方法來執行步驟和運行用例,如果沒有的話,會得到一個錯誤信息。
status()
Signature: status(Boolean asString)
新增於 1.0版本.
返回一個當前casper實例的狀態
casper.start('http://google.fr/', function() {
this.echo(this.status(true));
});
casper.run();
then()
Signature: then(Function then)
這個方法是增加一個執行步驟的標准方法:
casper.start('http://google.fr/');
casper.then(function() {
this.echo("I'm in your google.");
});
casper.then(function() {
this.echo('Now, let me write something');
});
casper.then(function() {
this.echo('Oh well.');
});
casper.run();
你能夠增加許多你需要的步驟,注意當前的casper實例自動綁定this
使用run()去執行你的步驟
提示:
為了使用then()你必須先使用一個start()
訪問當前HTTP響應
新增於1.0版本
你能夠讀取當前http響應對象,通過使用step回調的第一個參數:
casper.start('http://www.google.fr/', function(response) {
require('utils').dump(response);
});
能得到的:
$ casperjs dump-headers.js
{
"contentType": "text/html; charset=UTF-8",
"headers": [
{
"name": "Date",
"value": "Thu, 18 Oct 2012 08:17:29 GMT"
},
{
"name": "Expires",
"value": "-1"
},
// ... lots of other headers
],
"id": 1,
"redirectURL": null,
"stage": "end",
"status": 200,
"statusText": "OK",
"time": "2012-10-18T08:17:37.068Z",
"url": "http://www.google.fr/"
}
因此,也可以取得特定名稱的頭部:
casper.start('http://www.google.fr/', function(response) {
this.echo(response.headers.get('Date'));
});
得到如下結果:
$ casperjs dump-headers.js Thu, 18 Oct 2012 08:26:34 GMT
注意:
step方法添加到then()有兩種不同的處理方式:
1、先前的步驟已經被執行
2、先前的http請求已經執行並且頁面已經下載完成
請注意,沒有一個加載頁面的單一的定義,什么時候domready事件被觸發?什么時候所有的請求完成?什么時候所有的應用邏輯執行完成?或者所有的元素被渲染?這個答案依賴於上下文,因此,我們鼓勵使用waitfor*()系列的方法來控制你的期望。
一個常見的使用waitForSelector()的方法:
casper.start('http://my.website.com/');
casper.waitForSelector("#plop", function() {
this.echo("I'm sure #plop is available in the DOM");
});
casper.run();
thenBypass()
Signature: thenBypass(Number nb)
新增於 1.1版本
增加一個導航步驟,將繞過給定數量的步驟:
casper.start('http://foo.bar/');
casper.thenBypass(2);
casper.then(function() {
// This test won't be executed
});
casper.then(function() {
// Nor this one
});
casper.then(function() {
// While this one will
});
casper.run();
thenBypassIf()
Signature: thenBypassIf(Mixed condition, Number nb)
新增於 1.1版本
增加一個導航步驟,如果condition 為true或者執行的方法返回true,將繞過給定數量的步驟,:
var universe = {
answer: 42
};
casper.start('http://foo.bar/');
casper.thenBypassIf(function() {
return universe && universe.answer === 42;
}, 2);
casper.then(function() {
// This step won't be executed as universe.answer is 42
});
casper.then(function() {
// Nor this one
});
casper.then(function() {
// While this one will
});
casper.run();
thenBypassUnless()
Signature: thenBypassUnless(Mixed condition, Number nb)
新增於 1.1版本
和 thenBypassIf()相反。
thenClick()
Signature: thenClick(String selector[, Function then])
增加一個導航步驟去點擊一個執行的元素,並且增加一個新的導航步驟去單步執行:
// Click the first link in the casperJS page
casper.start('http://casperjs.org/').thenClick('a', function() {
this.echo("I clicked on first link found, the page is now loaded.");
});
casper.run();
這是一個便捷的方法,同時調用了then()和click()
thenEvaluate()
Signature: thenEvaluate(Function fn[, arg1[, arg2[, …]]])
增加一個導航步驟在當前的頁面DOM環境下執行javascript代碼:
// Querying for "Chuck Norris" on Google
casper.start('http://google.fr/').thenEvaluate(function(term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, 'Chuck Norris');
casper.run();
這是一個便捷的方法,同時調用了then()和evaluate()
thenOpen()
Signature: thenOpen(String location[, mixed options])
Adds a new navigation step for opening a new location, and optionally add a next step when its loaded:
增加一個打開新的URL的導航步驟,並且在下載完成后,執行下一步
casper.start('http://google.fr/').then(function() {
this.echo("I'm in your google.");
});
casper.thenOpen('http://yahoo.fr/', function() {
this.echo("Now I'm in your yahoo.")
});
casper.run();
新增於1.0版本
你可以在第二個參數中指明請求的設置:
casper.start().thenOpen('http://url.to/some/uri', {
method: "post",
data: {
username: 'chuck',
password: 'n0rr15'
}
}, function() {
this.echo("POST request has been sent.")
});
casper.run();
thenOpenAndEvaluate()
Signature: thenOpenAndEvaluate(String location[, Function then[, arg1[, arg2[, …]]])
他是一個打開URL和執行遠程dom環境代碼的快捷方法:
casper.start('http://google.fr/').then(function() {
this.echo("I'm in your google.");
});
casper.thenOpenAndEvaluate('http://yahoo.fr/', function() {
var f = document.querySelector('form');
f.querySelector('input[name=q]').value = 'chuck norris';
f.submit();
});
casper.run(function() {
this.debugPage();
this.exit();
});
toString()
Signature: toString()
新增於1.0版本
返回當前casper實例的字符串
casper.start('http://google.fr/', function() {
this.echo(this); // [object Casper], currently at http://google.fr/
});
casper.run();
unwait()
Signature: unwait()
新增於1.1版本
中斷所有當前等待的進程,如果有的話
userAgent()
Signature: userAgent(String agent)
新增於1.0版本
Sets the User-Agent string to send through headers when performing requests:
設置user-agent字符串,當你發送執行請求的包頭時
casper.start();
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');
casper.thenOpen('http://google.com/', function() {
this.echo("I'm a Mac.");
this.userAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
});
casper.thenOpen('http://google.com/', function() {
this.echo("I'm a PC.");
});
casper.run();
viewport()
Signature: viewport(Number width, Number height[, Function then])
改變當前窗口的尺寸
casper.viewport(1024, 768);
要確認你的頁面已經處理完成,你可以異步的使用它:
casper.viewport(1024, 768).then(function() {
// new view port is now effective
});
新增於1.1版本
在1.1版本,你可以直接使用 viewport()方法作為一個步驟:
casper.viewport(1024, 768, function() {
// new view port is effective
});
提示:
PhantomJS默認的窗口為400*300,casperjs默認繼承了它
visible()
Signature: visible(String selector)
檢查選擇器表達式匹配的DOM元素在遠程頁面是可用的:
casper.start('http://google.com/', function() {
if (this.visible('#hplogo')) {
this.echo("I can see the logo");
} else {
this.echo("I can't see the logo");
}
});
wait()
Signature: wait(Number timeout[, Function then])
在給定的時間后,阻止步驟繼續執行,並且在選項里執行一個步驟:
casper.start('http://yoursite.tld/', function() {
this.wait(1000, function() {
this.echo("I've waited for a second.");
});
});
casper.run();
你也可以用這種方式來實現:
casper.start('http://yoursite.tld/');
casper.wait(1000, function() {
this.echo("I've waited for a second.");
});
casper.run();
waitFor()
Signature: waitFor(Function testFx[, Function then, Function onTimeout, Number timeout, Object details])
Waits until a function returns true to process any next step.
等待,知道一個方法返回true,再繼續下一步
你也可以通過onTimeout設置一個超時的回調,並且設置一個毫秒計數的timeout用來進行超時退出,默認的超時是5000毫秒
casper.start('http://yoursite.tld/');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('ul.your-list li').length > 2;
});
}, function then() {
this.captureSelector('yoursitelist.png', 'ul.your-list');
});
casper.run();
執行onTimeout回調的實例:
casper.start('http://yoursite.tld/');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('ul.your-list li').length > 2;
});
}, function then() { // step to execute when check() is ok
this.captureSelector('yoursitelist.png', 'ul.your-list');
}, function timeout() { // step to execute if check has failed
this.echo("I can't haz my screenshot.").exit();
});
casper.run();
details 是一個waitFor.timeout事件傳遞的信息屬性包,它能夠用來獲取更明確的錯誤信息,或者有條件的忽略一些超時事件
waitForAlert()
Signature: waitForAlert(Function then[, Function onTimeout, Number timeout])
新增於1.1-beta4版本.
等待直到JavaScript alert被觸發,這個步驟會把alert的消息傳到response.data屬性里
casper.waitForAlert(function(response) {
this.echo("Alert received: " + response.data);
});
waitForPopup()
Signature: waitForPopup(String|RegExp urlPattern[, Function then, Function onTimeout, Number timeout])
新增於 1.0版本.
等待一個popup控件(彈出式窗口)被打開和加載
當前加載的彈出式窗口,有可用的casper.popups的類數組屬性:
casper.start('http://foo.bar/').then(function() {
this.test.assertTitle('Main page title');
this.clickLabel('Open me a popup');
});
// this will wait for the popup to be opened and loaded
casper.waitForPopup(/popup\.html$/, function() {
this.test.assertEquals(this.popups.length, 1);
});
// this will set the popup DOM as the main active one only for time the
// step closure being executed
casper.withPopup(/popup\.html$/, function() {
this.test.assertTitle('Popup title');
});
// next step will automatically revert the current page to the initial one
casper.then(function() {
this.test.assertTitle('Main page title');
});
waitForResource()
Signature: waitForResource(String|Function|RegExp testFx[, Function then, Function onTimeout, Number timeout])
等待直到一個匹配testFx的元素出現,然后執行下一個步驟
testFx參數即可以是一個字符串,也可以是一個方法,也可以是一個正則表達式:
casper.waitForResource("foobar.png", function() {
this.echo('foobar.png has been loaded.');
});
使用正則表達式:
casper.waitForResource(/foo(bar|baz)\.png$/, function() {
this.echo('foobar.png or foobaz.png has been loaded.');
});
使用方法:
casper.waitForResource(function testResource(resource) {
return resource.url.indexOf("https") === 0;
}, function onReceived() {
this.echo('a secure resource has been loaded.');
});
waitForUrl()
Signature: waitForUrl(String|RegExp url[, Function then, Function onTimeout, Number timeout])
新增於 1.1版本.
等待直到當前的頁面URL和給定的參數匹配(字符串或者正則表達式):
casper.start('http://foo/').waitForUrl(/login\.html$/, function() {
this.echo('redirected to login.html');
});
casper.run();
waitForSelector()
Signature: waitForSelector(String selector[, Function then, Function onTimeout, Number timeout])
等待直到在遠程dom環境下找到選擇器匹配的元素,然后進入下一步驟。使用方法和waitFor()一樣:
casper.start('http://foo.bar/');
casper.waitWhileSelector('.selector', function() {
this.echo('.selector is no more!');
});
casper.run();
waitForSelectorTextChange()
Signature: waitForSelectorTextChange(String selectors[, Function then, Function onTimeout, Number timeout])
等待直到選擇器表達式匹配的元素的文本變成了不同的值,然后進入下一步驟。使用方法和waitFor()一樣:
casper.start('http://foo.bar/');
casper.waitForSelectorTextChange('.selector', function() {
this.echo('The text on .selector has been changed.');
});
casper.run();
waitForText()
Signature: waitForText(String text[, Function then, Function onTimeout, Number timeout])
新增於 1.0版本.
等待直到text傳入的值包含在當前文本中,然后進入下一步驟,使用方法和waitFor()一樣:
waitUntilVisible()
Signature: waitUntilVisible(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression is visible in the remote DOM to process a next step. Uses waitFor().
等待直到選擇器表達式匹配的元素變成了不可用,然后進入下一步驟,使用方法和waitFor()一樣:
warn()
Signature: warn(String message)
記錄日志,並且打印一個警告消息到標准輸出中:
casper.warn("I'm a warning message.");
提示:
調用warn()將會執行warn事件
withFrame()
Signature: withFrame(String|Number frameInfo, Function then)
新增於1.0版本.
根據傳入的name或者index索引值,從主頁面切換到frame,然后執行下一步驟:
這個頁面的上下文切換僅持續到該步驟執行完成
casper.start('tests/site/frames.html', function() {
this.test.assertTitle('FRAMESET TITLE');
});
casper.withFrame('frame1', function() {
this.test.assertTitle('FRAME TITLE');
});
casper.withFrame(0, function() {
this.test.assertTitle('FRAME TITLE');
});
casper.then(function() {
this.test.assertTitle('FRAMESET TITLE');
});
withPopup()
Signature: withPopup(Mixed popupInfo, Function then)
新增於1.0版本.
根據傳入的信息,從主頁面切換到彈出式窗口,然后執行下一步驟:
這個頁面的上下文切換僅持續到該步驟執行完成:
casper.start('http://foo.bar/').then(function() {
this.test.assertTitle('Main page title');
this.clickLabel('Open me a popup');
});
// this will wait for the popup to be opened and loaded
casper.waitForPopup(/popup\.html$/, function() {
this.test.assertEquals(this.popups.length, 1);
});
// this will set the popup DOM as the main active one only for time the
// step closure being executed
casper.withPopup(/popup\.html$/, function() {
this.test.assertTitle('Popup title');
});
// next step will automatically revert the current page to the initial one
casper.then(function() {
this.test.assertTitle('Main page title');
});
提示:
當前的彈出式窗口,可以在Casper.popups中查詢到屬性值
zoom()
Signature: zoom(Number factor)
新增於1.0版本.
設置當前頁面的縮放比例:
var casper = require('casper').create();
casper.start().zoom(2).thenOpen('http://google.com', function() {
this.capture('big-google.png');
});
casper.run();
