[译文]casperjs的API-clientutils模块

casper提供了少量的客户端接口用来进行远程DOM环境注入,通过clientutils模块的ClientUtils类实例中的__utils__对象来执行:

casper.evaluate(function() {
  __utils__.echo("Hello World!");
});
提示:
这个工具不需要使用jQuery, Mootools等第三方库,但是不影响你通过Casper.options.clientScripts来使用这些第三方库
 

Bookmarklet(标签页)

一个标签页也能够帮助你在你熟悉的浏览器中使用casper的客户端接口。

只需要拖拽下面的标签到工具栏,然后点击它,一个__utils__对象已经在控制台里了

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);}}());})();

注:这里的用法不是很明白,CasperJS Utils链接实际的内容是一个javascript执行语句,作用是生成一个带有__uitls__对象的页面,使用户可以在浏览器控制台调试__utils__的功能,我的理解是如此,如果觉得疑惑的可以去看官方网站说明

提示:

CasperJS和PhantomJS基于webkit,你在使用标签页时最好使用最新的基于webkit的浏览器(如chrome,safari等)

ClientUtils 原型

echo()

Signature: echo(String message)

新增于1。0版本.

从远程DOM环境打印一个消息到casper控制台

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 will be 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 strings encoded using >8b characters:

使用base64编码编码一个字符串,为什么这么做?CasperJS不能使用内置的window.btoa()方法,因为它不能有效的处理使用了 >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:

检查给定的选择器表达式是否能匹配到一个DOM元素:

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:

获得根据给定的选择器表达式匹配的所有元素:

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(JSON.stringify(links)).exit();
});
findOne()

Signature: findOne(String selector)

Retrieves a single DOM element by a 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 will retrieved a base64 encoded version of any resource behind a url. For example, let’s imagine we want to retrieve the base64 representation of some website’s logo:

这个方法用来获得一个URL链接后面的资源,并且将该资源转码为base64格式,例如,让我们想象我们想得到一些网站的logo base64表示:

var logo = null;
casper.start('http://foo.bar/', function() {
    logo = this.evaluate(function() {
        var imgUrl = document.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 will 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 environment. If you intend to download the resource, use getBase64() or Casper.base64encode() instead:

这个方法用来获取一个二进制文件的原始内容,因为PhantomJS不能直接处理这些数据,所以你智能在远程DOM环境中进行处理,如果你计划下载这些资源,使用getBase64() 或者 Casper.base64encode() 来替代:

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()

新增于1.0版本.

获取当前的文档高度:

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.

获取给定选择器匹配的一个元素的边界值

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

如果匹配到元素,返回一个拥有top,left,width,height的对象,如果没有匹配到元素,返回null

getElementsBounds()

Signature: getElementsBounds(String selector)

Retrieves boundaries for all DOM element matching the provided selector.

获取给定选择器匹配的所有元素的边界值

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

如果匹配到元素,返回一个列表,列表中的对象都拥有top,left,width,height属性

getElementByXPath()

Signature: getElementByXPath(String expression [, HTMLElement scope])

获取一个给定xpath选择器匹配的元素

新增于1.0版本

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

scope参数允许你设置执行xpath查询的上下文。

// will be performed against the whole document
__utils__.getElementByXPath('.//a');

// will be performed against a given DOM 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.

获取给定xpath选择器匹配的所有元素,如果它有的话

新增于1.0版本

scope参数允许你设置执行xpath查询的上下文。

 

getFieldValue()

Signature: getFieldValue(String inputName[, Object options])

新增于1.0版本

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

获取值,从表单的元素中获取对应的值

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

对”plop”使用getFieldValue()方法:

__utils__.getFieldValue('plop'); // 42
选项:
  • formSelector:允许为表单包含的元素设置选择器
getFormValues()

Signature: getFormValues(String selector)

新增于1.0版本

获取表单中所有元素的值:

<form id="login" action="/login">
    <input type="text" name="username" value="foo">
    <input type="text" name="password" value="bar">
    <input type="submit">
</form>
获取表单中的值:
__utils__.getFormValues('form#login'); // {username: 'foo', password: 'bar'}
 
log()

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

Logs a message with an optional level. Will format the message a way CasperJS will be able to log phantomjs side. Default level is debug:

记录一个选定级别的消息,这个消息将格式化为phantomjs 的消息,默认级别为debug

mouseEvent()

Signature: mouseEvent(String type, String selector)

给选定的dom元素上发起一个鼠标事件

支持的事件有mouseup, mousedown, click, mousemove, mouseovermouseout.

removeElementsByXPath()

Signature: removeElementsByXPath(String expression)

Removes all DOM elements matching a given XPath expression.

移除给定的xpath选择器匹配的所有dom元素

sendAJAX()

Signature: sendAJAX(String url[, String method, Object data, Boolean async, Object settings])

新增于1.0版本

发送一个AJAX请求,使用如下参数:

  • url: 请求的URL
  • method:HTTP方法(默认: GET).
  • data:请求参数 (默认: null).
  • async:是否同步请求的标志 (默认: false)
  • settings: 执行AJAX请求的其他设置(默认: null)

注意:

不要忘记设置--web-security=no 选项在命令行执行时,如果你需要跨域的话:

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)

将选定的元素设置为不可用:

var logoIsVisible = casper.evaluate(function() {
    return __utils__.visible('h1');
});
原文地址:https://www.cnblogs.com/reach296/p/3868599.html