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; 所有可用的屬性如下: clientScriptsType: Array Default: [] 一個本地script指令檔路徑的集合,它們能被載入到所有頁面 exitOnErrorType: Boolean Default: true 如果CasperJS的指令碼在運行過程中出現一個uncaught error ,那麼casperjs運行結束 httpStatusHandlersType: Object Default: {} 一個javascript對象,他包含了一個擷取到指定http狀態的就觸發執行的回調方法,使用方法已經包含在例子中了 logLevelType: String Default: "error" 日誌等級 onAlertType: Function Default: null 當一個javascript 的alert()被觸發時的回調方法 onDieType: Function Default: null 當Casper#die() 被觸發時的回調方法 onErrorType: Function Default: null 當一個“error”等級的事件被觸發時的回調方法 onLoadErrorType: Function Default: null 請求的資源沒有被load下來時被觸發的回調方法 onPageInitializedType: Function Default: null 頁面已經被初始化後被觸發的回調方法 onResourceReceivedType: Function Default: null 該方法替換了PhantomJS的WebPage#onResourceReceived()的回調,只要正確的casper執行個體作為第一個參數被傳入 onResourceRequestedType: Function Default: null 該方法替換了PhantomJS的WebPage#onResourceRequested()的回調,只要正確的casper執行個體作為第一個參數被傳入 onStepCompleteType: Function Default: null 當一個step方法已經執行完成後,這個方法被執行 onStepTimeoutType: Function Default: Function 當一個step方法在執行逾時後,如果設定了這個方法,這個方法將被執行 預設情況下,指令碼會退出並顯示一個錯誤,如果是在test環境中,它將會增加一個失敗到測試結果中。 onTimeoutType: Function Default: Function 當指令碼在執行時,超過了option設定的timeout值後,如果設定了這個方法,這個方法將被執行 預設情況下,逾時的指令碼將會退出並顯示錯誤,如果是在test環境中,它將會增加一個失敗到測試結果中。 onWaitTimeoutType: Function Default: Function 當一個waitFor*方法在執行時,超過了設定的waitTimeout 值後,如果設定了這個方法,這個方法將被執行 預設情況下,逾時的指令碼將會退出並顯示錯誤,如果是在test環境中,它將會增加一個失敗到測試結果中。 pageType: WebPage Default: null 一個存在於PhantomJS的 webPage執行個體 pageSettingsType: Object Default: {} PhantomJS的 webPage執行個體,可用的設定如下: javascriptEnabled 定義了頁面是否執行script指令碼 (預設為true)loadImages 定義了是否載入圖片(預設為true)loadPlugins 定義了是否載入 NPAPI 外掛程式 (Flash, Silverlight, …)localToRemoteUrlAccessEnabled 定義了本地資源是否可以上傳(預設為 false)userAgent 定義了頁面請求伺服器資源時的userAgentuserName 設定http認證的使用者名稱password 設定http認證的密碼XSSAuditingEnabled 定義是否能發起跨域請求(預設為 false)remoteScriptsType: Array Default: [] 新增於1.0版本 一個遠程script指令檔路徑的集合,它們能被載入到所有頁面 safeLogsType: Boolean Default: true 新增於1.0版本 當這個屬性設定為true,從<input type=”password”> 獲得的密碼資訊將不被明文顯示出來,它是預設為true,設定safelogs為false,密碼會被明文顯示(不推薦) silentErrorsType: 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. 當這個選項是可用的,會導致步驟錯誤不會被拋出,一般使用者測試架構中 stepTimeoutType: Number Default: null 用毫秒計算的最大step逾時時間,當設定以後,每個定義的step方法都將在逾時時間到達以前執行完成,你可以定義onStepTimeout() 回調方法來捕獲這種情況,預設情況下,這個指令碼將會拋出一個錯誤資訊並結束 timeoutType: Number Default: null 用毫秒計算的最大逾時時間 verboseType: Boolean Default: false 即時輸出log資訊 viewportSizeType: Object Default: null 視窗尺寸, eg. {width: 800, height: 600} 提示: phantomjs預設的視窗尺寸為400*300, casperjs繼承了這個尺寸 retryTimeoutType: Number Default: 100 重試時的預設延遲間隔時間,在 wait*系列的方法中生效 waitTimeoutType: Number Default: 5000 預設的等待逾時時間,在 wait*系列的方法中生效 Casper prototypeback()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到100clear()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()方法