[]casperjs api-clientutils Module

Source: Internet
Author: User
Tags findone xpath

Casper provides a small number of client interfaces for remote DOM environment injection through the __utils__ object in the Clientutils class instance of the Clientutils module:

Casper.evaluate (function () {  __utils__.echo ("Hello world!");});
Tips:
This tool does not require the use of third-party libraries such as jquery, MooTools, etc., but does not affect your use of these third-party libraries through Casper.options.clientScripts
Bookmarklet (Label page)

A tab can also help you use the Casper Client interface in your familiar browser.

Just drag and drop the following tab to the toolbar, then click on it, and a __utils__ object is already in the console.

Casperjs Utils

JavaScript: (function () {void (function () {if (!document.getelementbyid (' casperutils ')) {var%20casperutils= Document.createelement (' script '); Casperutils.id= ' casperutils '; casperutils.src= ' Https://raw.github.com/n1k0/casperjs/master/modules/clientutils.js '; Document.documentElement.appendChild (casperutils); Var%20interval=setinterval (function () {if (typeof% 20clientutils=== ' function ') {Window.__utils__=new%20window. Clientutils (); clearinterval (interval);}},50);} ());}) ();

Note: The usage here is not very clear, Casperjs utils link The actual content is a JavaScript execution statement, the role is to generate a page with __uitls__ object, so that the user can debug in the browser console __utils__ function, I understand that, If you feel confused, you can visit the official website.

Tips:

Casperjs and PHANTOMJS based on WebKit, you should use the latest WebKit-based browsers (such as Chrome,safari, etc.) when using tabs.

clientutilsPrototypeEcho ()

Signature: Echo (String message)

Added on 1. Version 0.

Print a message from the remote DOM environment to the Casper console

Print a message out to the Casper console from the remote page DOM environment:

Casper.start (' http://foo.ner/'). Thenevaluate (function () {    __utils__.echo (' plop ');//This would be the printed to your Shell at runtime});
encode ()

Signature: encode (String contents)

Encodes a string using the Base64 algorithm. For the records, Casperjs doesn ' t use builtin window.btoa () function because it can ' t deal efficiently with Strin GS encoded using >8B characters:

Encode a string using Base64 encoding, why do you do this? Casperjs cannot use the built-in Window.btoa () method because it cannot effectively handle strings that use >8b

var base64;casper.start (' http://foo.bar/', function () {    base64 = this.evaluate (function () {        return __utils__. Encode ("I ' ve been a bit cryptic recently");});    Casper.run (function () {    This.echo (base64). exit ();});
exists ()

Signature: exists (String selector)

Checks if a DOM element matching a given selector expression exists:

Checks whether a given selector expression can match to a DOM element:

var exists;casper.start (' http://foo.bar/', function () {    exists = this.evaluate (function () {        return __utils_ _.exists (' #some_id ');})    ; Casper.run (function () {    This.echo (exists). exit ();});
findAll ()

Signature: findAll (String selector)

Retrieves all DOM elements matching a given selector expression:

Gets all the elements that match the given selector expression:

var links;casper.start (' http://foo.bar/', function () {    links = this.evaluate (function () {        var elements = __ Utils__.findall (' A.menu ');        return Array.prototype.forEach.call (elements, function (e) {            return E.getattribute (' href ');        });});    Casper.run (function () {    This.echo (links)). exit ();});
FindOne ()

Signature: FindOne (String selector)

Retrieves a single DOM element by a selector expression:

Gets a single element that matches the given selector expression:

var href;casper.start (' http://foo.bar/', function () {    href = this.evaluate (function () {        return __utils__. FindOne (' #my_id '). getattribute (' href ');    }); Casper.run (function () {    this.echo (href). exit ();});
getBase64 ()

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

This method would retrieved a base64 encoded version of any resource behind a URL. For example, let's imagine we want to retrieve the base64 representation of the some website ' s logo:

This method is used to get a resource behind a URL link and transcode the resource to Base64 format, for example, let's imagine we want to get some website logo base64 said:

var logo = Null;casper.start (' http://foo.bar/', function () {    logo = this.evaluate (function () {        var imgurl = Docum Ent.queryselector (' Img.logo '). getattribute (' src ');        Return __utils__.getbase64 (Imgurl);    }); Casper.run (function () {    This.echo (logo). exit ();});
getbinary ()

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

This method would retrieved the raw contents of a given binary resource; Unfortunately though, PHANTOMJS cannot process these data directly so you'll have to process them within the remote DOM en Vironment. If you intend to download the resource, use GetBase64 () or casper.base64encode () instead:

This method is used to get the original content of a binary file, because PHANTOMJS cannot process the data directly, so you intelligently handle it in a remote DOM environment, and if you plan to download these resources, use GETBASE64 () or Casper.base64encode () to replace:

Casper.start (' http://foo.bar/', function () {    this.evaluate (function () {        var imgurl = Document.queryselector ( ' Img.logo '). getattribute (' src ');        Console.log (__utils__.getbinary (Imgurl));})    ; Casper.run ();
getdocumentheight ()

Signature: getdocumentheight ()

Added in version 1.0.

Gets the current document height:

var documentheight;casper.start (' http://google.com/', function () {    documentheight = this.evaluate (function () {        return __utils__.getdocumentheight ();    });    This.echo (' Document height is ' + documentheight + ' px ');}); Casper.run ();
etelementbounds ()

Signature: getelementbounds (String selector)

Retrieves boundaries for a DOM elements matching the provided selector.

Gets the boundary value of an element that is matched by a given selector

It returns an Object with four keys: top, left, width and height, or null if the selector doesn ' t exist.

Returns an object that owns Top,left,width,height if it matches to an element, and returns null if there is no match to the element

getelementsbounds ()

Signature: getelementsbounds (String selector)

Retrieves boundaries for all DOM element matching the provided selector.

Gets the boundary value of all elements that a given selector matches

It returns an array of objects each have four keys: top, left, width and height.

If a match is to an element, returns a list of objects in the list that have the Top,left,width,height property

Getelementbyxpath ()

Signature: Getelementbyxpath (String expression [, htmlelement scope])

Gets an element that matches the given XPath selector

Added in version 1.0

The scope argument allow to set the context for executing the XPath query:

The scope parameter allows you to set the context in which the XPath query is executed.

would be performed against the whole Document__utils__.getelementbyxpath ('.//a ');//would be performed against a given do M Element__utils__.getelementbyxpath ('.//a ', __utils__.findone (' Div.main '));
Getelementsbyxpath ()

Signature: Getelementsbyxpath (String expression [, htmlelement scope])

Retrieves all DOM elements matching a given XPath expression, if any.

Gets all the elements that match the given XPath selector, if it has one

Added in version 1.0

The scope parameter allows you to set the context in which the XPath query is executed.

GetFieldValue ()

Signature: GetFieldValue (String inputname[, Object options])

Added in version 1.0

Retrieves the value from the field named against the inputnamed argument:

Gets the value that gets the corresponding value from the element in the form

<form>    <input type= "text" name= "plop" value= "></form>"

Use the GetFieldValue () method for "Plop":

__utils__.getfieldvalue (' plop '); 42
Options:
    • formselector: Allows you to set selectors for elements contained in a form
getformvalues ()

Signature: getformvalues (String selector)

Added in version 1.0

Get the values of all the elements in the form:

<form id= "Login" action= "/login" >    <input type= "text" name= "username" value= "foo" >    <input Type = "text" name= "password" value= "bar" >    <input type= "Submit" ></form>
Get the values in the form:
__utils__.getformvalues (' Form#login '); {username: ' foo ', Password: ' Bar '}
log ()

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

Logs a message with the optional level. Would format the message a-casperjs would be able to log Phantomjs side. Default level is debug:

Records a selected level of messages that are formatted as PHANTOMJS messages, with the default level of debug

mouseEvent ()

Signature: mouseEvent (String type, string selector)

Initiates a mouse event on the selected DOM element

Supported events are MouseUp, mousedown, click, mousemove, mouseover and mouseout .

Removeelementsbyxpath ()

Signature: Removeelementsbyxpath (String expression)

Removes all DOM elements matching a given XPath expression.

Removes all DOM elements that are matched by the given XPath selector

Sendajax ()

Signature: Sendajax (String url[, String method, Object data, Boolean async, Object Settings])

Added in version 1.0

Send an AJAX request using the following parameters:

    • URL: Requested URL
    • Method: HTTP Methods (default: GET).
    • data: Request parameter (default: null).
    • Async: Whether the requested flag is synchronized (default: false)
    • Settings: Additional settings to perform AJAX requests (default: null)

Attention:

Do not forget to set the --web-security=no option at the command line if you need to cross the domain:

var data, Wsurl = ' Http://api.site.com/search.json '; Casper.start (' http://my.site.com/', function () {    data = This.evaluate (function (wsurl) {        return Json.parse (__utils__.sendajax (Wsurl, ' GET ', NULL, false));    }, { Wsurl:wsurl}); Casper.then (function () {    require (' utils '). dump (data);});
visible ()

Signature: visible (String selector)

Set the selected element to be unavailable:

var logoisvisible = casper.evaluate (function () {    return __utils__.visible (' H1 ');});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.