Casperjs API-casper Module
Casper class: You can use the create () method of this module to obtain an instance of this module, which is the easiest: var casper = require ('casper '). create (); you can also obtain an instance by instantiating the main method: var casper = new require ('casper '). casper (); prompt: If the casper class is extended, a parameter option is accepted for both the casper constructor and the create () method. The standard javascript Object is the same. Var casper = require ('casper '). create ({verbose: true, logLevel: "debug"}); Casper. options an options object can be passed into the casper constructor. For example, var casper = require ('casper '). create ({clientScripts: ['regiondes/jquery. js', // These two scripts will be injected in remote 'Using DES/underscore. js' // DOM on every request], pageSettings: {loadImages: false, // The WebPage instance used by Casper will loadPlugins: false // u Se these settings}, logLevel: "info", // Only "info" level messages will be logged verbose: true // log messages will be printed out to the console }); you can also change options in the runtime: var casper = require ('casper '). create (); casper. options. waitTimeout = 1000; All available attributes are as follows: clientScriptsType: Array Default: [] a collection of local script file paths, which can be loaded to all pages exitOnErrorType: Boolean Default: true: If the CasperJS script displays an uncaught err during running Or, then casperjs finishes running httpStatusHandlersType: Object Default: {} A javascript Object, which contains a callback method that triggers execution when the specified http status is obtained, the usage has been included in the example. logLevelType: String Default: "error" Log Level onAlertType: Function Default: null the callback method onDieType when a javascript alert () is triggered: function Default: null callback method onErrorType: Function Default: null when an "error" Level event is triggered onLoadErrorType: function Default: The resource requested by null is not lo The callback method onPageInitializedType: Function Default: null when the ad is down. The callback method onResourceReceivedType: Function Default: triggered after the page is initialized: null this method replaces the callback of WebPage # onResourceReceived () of PhantomJS, as long as the correct casper instance is passed as the first parameter onResourceRequestedType: Function Default: null this method replaces the callback of WebPage # onResourceRequested () of PhantomJS. If the correct casper instance is passed as the first parameter, onStepCompleteType: Function Default: null when a step method has been executed, this method is executed onStepTimeoutT Ype: Function Default: Function when the execution of a step method times out, if this method is set, this method is executed. By Default, the script exits and an error is displayed, if it is in the test environment, it will add a failure to the test results. OnTimeoutType: Function Default: Function when the script is executed and exceeds the timeout value set by option, if this method is set, this method is executed by Default, the script that times out will exit and display an error. If it is in the test environment, it will add a failure to the test results. OnWaitTimeoutType: Function Default: Function when a waitFor * method is executed and exceeds the value of waitTimeout, if this method is set, this method is executed by Default, the script that times out will exit and display an error. If it is in the test environment, it will add a failure to the test results. PageType: WebPage Default: null A pageSettingsType: Object Default: {} PhantomJS webPage instance that exists in PhantomJS. The available settings are as follows: javascriptEnabled defines whether the page executes the script (true by default) loadImages defines whether to load the image (true by default) loadPlugins defines whether to load the NPAPI plug-in (Flash, Silverlight ,...) LocalToRemoteUrlAccessEnabled defines whether local resources can be uploaded (default: false) userAgent defines userAgentuserName for page requests to server resources set http Authentication Username password set http Authentication password XSSAuditingEnabled define whether cross-origin requests can be initiated (Default: false) remoteScriptsType: Array Default: [] added to version 1.0 A Collection of remote script file paths that can be loaded to all pages. safeLogsType: Boolean Default: true is added to version 1.0. When this attribute is set to true, the password information obtained from <input type = "password"> is not displayed in plain text. The default value is true. If the value of safelogs is set to false, the password is displayed in plain text (not recommended) silentErrorsT Ype: 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. if this option is available, step errors will not be thrown. Generally, in the user testing framework, stepTimeoutType: Number Default: null indicates the maximum step timeout time in milliseconds. After this option is set, each defined step method will be executed before the timeout time reaches. You can define the onStepTimeout () callback method to capture this situation. By default, this script will throw an error message and end the maximum timeoutType: Number Default: null in milliseconds. Time verboseType: Boolean Default: false Real-Time Output log information viewportSizeType: Object Default: null window size, eg. {width: 800, height: 600} tip: the Default window size of phantomjs is 400*300. casperjs inherits the Default delay interval of retryTimeoutType: Number Default: 100 retry, waitTimeoutType: Number Default: 5000 Default wait timeout in the wait * series method, effective in the wait * series method Casper prototypeback () Signature: back () moves back a step in browser's history: return the back step from the browser's history Er. 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'}); you can also view forward () base64encode () Signature: base64encode (String url [, String method, Object data]) encodes a resource using the base64 algorithm synchronously using client-side XMLHttpRequest. XMLHttpR for the client Equest for base64 encoding. Note: we cannot use window. btoa (), because it will cause a failure instance in webkit phantomjs: base64 encoding for google logo images: var base64logo = null; casper. start ('HTTP: // www. google. fr/', function () {base64logo = this. base64encode ('HTTP: // www. google. fr/images/srpr/logo3104png ');}); casper. run (function () {this. echo (base64logo ). exit () ;}); you can also encode the content of an http post request var base64contents = null; casper. start ('HTTP: // domain. tld/dow Nload.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) added in version 1.1 Bypasses a given number of defined navigation steps: Skip the specified number of steps casper. start (); casper. then (function () {// This step will be executed}); casper. then (function () {this. B Ypass (2) ;}); casper. then (function () {// This test won't be executed}); casper. then (function () {// Nor this one}); casper. run (); click () Signature: click (String selector) executes one click on the elements matching the expression. This method is used in two ways: try to trigger a Javascript MouseEvent event. If the previous method does not work, trigger a QtWebKit event instance: 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]) added in version 0.6.1 Clicks on the first DOM element found containing label text. optionaly en Sures that the element node name is tag: Click to match the first DOM element containing the specified text, or make sure that the node name of the element is a tag. // <a href = "... "> My link is beautiful </a> casper. then (function () {this. clickLabel ('My link is beauul ul ', '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 substitution method. add a clipRect parameter, which can set the page size casper. start ('HTTP: // www. google. fr/', function () {this.capture('google.png', {top: 100, left: 100, width: 500, height: 400}) ;}); casper. run (); added to imgOptions 1.1, two options can be specified: format is used to set the image format, so as to avoid setting the image quality based on the file name quality. For example: casper. start ('HTTP: // foo', function () {this. capture ('foo', undefined, {format: 'jpg ', qu Ality: 75}) ;}); captureBase64 () Signature: captureBase64 (String format [, Mixed area]) added at 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. A Base64 encoded binary screenshot. It can be used to capture all pages in a given format, or in a certain area of the screenshot page. These image formats are supported: bmp, jpg, jpeg, png, ppm, tiff, xbm, xpm. the area option can be in the following format: String: area is a CSS3 expression String, eg. div # plop form [name = "form"] Input [type = "submit"] clipRect: area is a clipRect object, eg. {"top": 0, "left": 0, "width": 320, "height": 200} Object: area is an expression Object, eg. an XPath selector instance: 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: the page is truncated based on the expression provided in the page area and saved as a target file casper. start ('HTTP: // www.weather.com/', function () {this.captureSelector('weather.png', '# wx-main');}); casper. run (); added to imgOptions 1.1 Two parameters, format, are set to set the image format to avoid setting the image quality based on the file name quality. values from 1 to 100 clear () Signature: clear () are added to 0.6.5. the execution environment context of the current page is clear to avoid the dom of the previous page still exists. It can be used as a way to stop javascript Execution in a remote DOM environment: 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]) outputs the getHTML () result to the console, which has the same parameters as getHTML. DebugPage () Signature: debugPage () Logs the textual contents of the current page directly to the standard output, for debugging purpose: records the text on the current page and outputs it to the standard output, it is mainly used to debug 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: When an error is recorded, exit phantom and set Exit status code 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 (): Save a remote resource file to the file system, you can set optional parameters and use method Set the http Request Method and use data to set the request parameter casper. start ('HTTP: // www. google. fr/', function () {var url = 'HTTP: // www. google. fr/intl/fr/about/initate/company/'; this. download (url, 'google_company.html ') ;}); casper. run (function () {this. echo ('done. '). exit () ;}); Note: If you have trouble downloading files, try not to use web security. each () Signature: each (Array array, Function fn) traverses the elements in the Array and executes a callback: var links = ['HTTP: // google.com/', 'HTTP: // yahoo.com /', 'HTTP: // bing.com/'success; casper. start (). each (links, function (self, link) {self. thenOpen (link, function () {this. echo (this. getTitle () ;};}); casper. run (); prompt: googlematch. js is an example of using it 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: traverse the elements in the array, add a step, and process it with elements: casper. start (). eachTh En ([1, 2, 3], function (response) {this. echo (response. data );}). run (); this is an example of opening a URL: var casper = require ('casper '). create (); var urls = ['HTTP: // google.com/', 'HTTP: // yahoo.com/'example; casper. start (). eachThen (urls, function (response) {this. thenOpen (response. data, function (response) {console. log ('opened', response. url) ;}); casper. run (); prompt: The current element will be stored in response. echo () Signature: echo (String messa Ge [, String style]) Prints something to stdout, optionally with some fancy color (see the colorizer module for more information): print something to the standard output, the optional parameter allows you to set the desired color 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 (Functio N fn [, arg1 [, arg2 [,…]) Based on PhantomJS 'webpage # evaluate, execute the javascript statement casper in the DOM environment of the current page. evaluate (function (username, password) {document. querySelector ('# username '). value = username; document. querySelector ('# password '). value = password; document. querySelector ('# submit '). click () ;}, 'sheldon. cooper ', 'b4z1ng4'); tip: If you are filling or submitting a form, it is best to use the fill () method.