var casper = require('casper').create();
咱們也能夠經過實例化主方法的方式得到一個自身的實例:
var casper = new require('casper').Casper();
提示:
若是擴展casper類,後面的章節會講到
不論是casper構造函數仍是create()方法,都接受一個參數選項,這個標準的javascript對象同樣。
var casper = require('casper').create({ verbose: true, logLevel: "debug" });
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;
全部可用的屬性以下:
Type: Arrayjavascript
Default: []php
一個本地script腳本文件路徑的集合,它們能被加載到全部頁面css
Type: Booleanhtml
Default: truejava
若是CasperJS的腳本在運行過程當中出現一個uncaught error ,那麼casperjs運行結束node
Type: Objectjquery
Default: {}css3
一個javascript對象,他包含了一個獲取到指定http狀態的就觸發執行的回調方法,使用方法已經包含在例子中了git
Type: Stringgithub
Default: "error"
日誌等級
Type: Function
Default: null
當一個javascript 的alert()被觸發時的回調方法
Type: Function
Default: null
當Casper#die() 被觸發時的回調方法
Type: Function
Default: null
當一個「error」等級的事件被觸發時的回調方法
Type: Function
Default: null
請求的資源沒有被load下來時被觸發的回調方法
Type: Function
Default: null
頁面已經被初始化後被觸發的回調方法
Type: Function
Default: null
該方法替換了PhantomJS的WebPage#onResourceReceived()的回調,只要正確的casper實例做爲第一個參數被傳入
Type: Function
Default: null
該方法替換了PhantomJS的WebPage#onResourceRequested()的回調,只要正確的casper實例做爲第一個參數被傳入
Type: Function
Default: null
當一個step方法已經執行完成後,這個方法被執行
Type: Function
Default: Function
當一個step方法在執行超時後,若是設置了這個方法,這個方法將被執行
默認狀況下,腳本會退出並顯示一個錯誤,若是是在test環境中,它將會增長一個失敗到測試結果中。
Type: Function
Default: Function
當腳本在執行時,超過了option設置的timeout值後,若是設置了這個方法,這個方法將被執行
默認狀況下,超時的腳本將會退出並顯示錯誤,若是是在test環境中,它將會增長一個失敗到測試結果中。
Type: Function
Default: Function
當一個waitFor*方法在執行時,超過了設置的waitTimeout 值後,若是設置了這個方法,這個方法將被執行
默認狀況下,超時的腳本將會退出並顯示錯誤,若是是在test環境中,它將會增長一個失敗到測試結果中。
Type: WebPage
Default: null
一個存在於PhantomJS的 webPage實例
Type: Object
Default: {}
PhantomJS的 webPage實例,可用的設置以下:
Type: Array
Default: []
新增於1.0版本
一個遠程script腳本文件路徑的集合,它們能被加載到全部頁面
Type: Boolean
Default: true
新增於1.0版本
當這個屬性設置爲true,從<input type=」password」> 得到的密碼信息將不被明文顯示出來,它是默認爲true,設置safelogs爲false,密碼會被明文顯示(不推薦)
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.
當這個選項是可用的,會致使步驟錯誤不會被拋出,通常用戶測試框架中
Type: Number
Default: null
用毫秒計算的最大step超時時間,當設置之後,每一個定義的step方法都將在超時時間到達之前執行完成,你能夠定義onStepTimeout() 回調方法來捕獲這種狀況,默認狀況下,這個腳本將會拋出一個錯誤信息並結束
Type: Number
Default: null
用毫秒計算的最大超時時間
Type: Boolean
Default: false
實時輸出log信息
Type: Object
Default: null
窗口尺寸, eg. {width: 800, height: 600}
提示:
phantomjs默認的窗口尺寸爲400*300, casperjs繼承了這個尺寸
Type: Number
Default: 100
重試時的默認延遲間隔時間,在 wait*系列的方法中生效
Type: Number
Default: 5000
默認的等待超時時間,在 wait*系列的方法中生效
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()
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(); });
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();
Signature: click(String selector)
對匹配表達式的元素執行一次點擊,這個方法用兩種方式進行嘗試:
實例:
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();
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'); });
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 對象容許指定兩個選項:
實例:
casper.start('http://foo', function() { this.capture('foo', undefined, { format: 'jpg', quality: 75 }); });
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選項能夠用如下的形式:
實例:
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();
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對象容許指定兩個參數
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();
Signature: debugHTML([String selector, Boolean outer])
向控制檯輸出getHTML()的結果,它和getHTML()具備一樣的參數。
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();
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();
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.
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是一個使用它的例子
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屬性裏
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();
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(),你就進入了瀏覽器控制檯,而且進入頁面執行代碼。
這是一個示意圖用來描述二者之間的關係
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();
Signature: exit([int status])
Exits PhantomJS with an optional exit status code.
退出phantomjs,而且返回一個退出狀態碼
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();
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();
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()
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();
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 }); });
注意:
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); });
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選擇器,這是他的限制
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();
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();
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();
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 }
Signature: getElementsBounds(String selector)
新增於1.0版本
獲取選擇器匹配的全部元素的區域信息的數組
它返回一個對象數組,對象包括如下四個鍵:top, left, width 和 height
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環境裏是不能直接獲取頁面裏的對象的
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環境裏是不能直接獲取頁面裏的對象的
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();
Signature: getGlobal(String name)
經過名稱,獲取遠程DOM環境下的一個全局變量的值,基本上,getGlobal('foo')意味着將從頁面得到window.foo的值:
casper.start('http://www.google.fr/', function() { this.echo(this.getGlobal('innerWidth')); // 1024 }); casper.run();
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>' });
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(); });
Signature: getTitle()
獲取當前頁面的標題
casper.start('http://www.google.fr/', function() { this.echo(this.getTitle()); // "Google" }); casper.run();
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();
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' } });
Signature: reload([Function then])
新增於1.0版本
刷新當前頁面的請求
casper.start('http://google.com', function() { this.echo("loaded"); this.reload(function() { this.echo("loaded again"); }); }); casper.run();
Signature: repeat(int times, Function then)
針對當前的步驟,重複執行指定的次數
casper.start().repeat(3, function() { this.echo("Badger"); }); casper.run();
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()方法。
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或調失敗時觸發
Signature: scrollTo(Number x, Number y)
新增於1.1-beat3版本
滾動當前文檔到根據x,y定義的指定的座標系:
casper.start('http://foo.bar/home', function() { this.scrollTo(500, 300); });
提示:
這個操做是同步的
Signature: scrollToBottom()
新增於 1.1-beta3版本
滾動到當前文檔的底部:
casper.start('http://foo.bar/home', function() { this.scrollToBottom(); });
提示:
這個操做是同步的
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元素
(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'}); });
可用的修飾語:
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();
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()方法來執行步驟和運行用例,若是沒有的話,會獲得一個錯誤信息。
Signature: status(Boolean asString)
新增於 1.0版本.
返回一個當前casper實例的狀態
casper.start('http://google.fr/', function() { this.echo(this.status(true)); }); casper.run();
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()有兩種不一樣的處理方式:
一、先前的步驟已經被執行
二、先前的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();
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();
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();
Signature: thenBypassUnless(Mixed condition, Number nb)
新增於 1.1版本
和 thenBypassIf()相反。
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()
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()
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();
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(); });
Signature: toString()
新增於1.0版本
返回當前casper實例的字符串
casper.start('http://google.fr/', function() { this.echo(this); // [object Casper], currently at http://google.fr/ }); casper.run();
Signature: unwait()
新增於1.1版本
中斷全部當前等待的進程,若是有的話
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();
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默認繼承了它
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"); } });
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();
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事件傳遞的信息屬性包,它可以用來獲取更明確的錯誤信息,或者有條件的忽略一些超時事件
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); });
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'); });
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.'); });
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();
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();
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();
Signature: waitForText(String text[, Function then, Function onTimeout, Number timeout])
新增於 1.0版本.
等待直到text傳入的值包含在當前文本中,而後進入下一步驟,使用方法和waitFor()同樣:
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()同樣:
Signature: warn(String message)
記錄日誌,而且打印一個警告消息到標準輸出中:
casper.warn("I'm a warning message.");
提示:
調用warn()將會執行warn事件
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'); });
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中查詢到屬性值
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();