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

[译文]casperjs的API-clientutils模块的更多相关文章

  1. [译文]casperjs的API-colorizer模块

    colorizer模块包含了一个Colorizer类,它能够生成一个标准化的颜色字符串: var colorizer = require('colorizer').create('Colorizer' ...

  2. [译文]casperjs 的API-casper模块

    Casper class: 可以通过这个模块的create()方法来获取这个模块的一个实例,这是最容易的: var casper = require('casper').create(); 我们也可以 ...

  3. [译文]casperjs的API-mouse模块

    mouse类 这个类是对各种鼠标操作的抽象,比如移动,点击,双击,滚动等.它要求一个已经获得DOM属性的casper对象,能用这种方式创造一个鼠标对象: var casper = require(&q ...

  4. [译文]casperjs使用说明-使用命令行

    使用命令行 Casperjs使用内置的phantomjs命令行解析器,在cli模块里,它传递参数位置的命名选项 但是不要担心不能熟练操控CLI模块的API,一个casper实例已经包含了cli属性,允 ...

  5. JavaScript 客户端JavaScript之事件(DOM API 提供模块之一)

    具有交互性的JavaScript程序使用的是事件驱动的程序设计模型.   目前使用的有3种完全不同的不兼容的事件处理模型. 1.原始事件模型 (一种简单的事件处理模式) 一般把它看作0级DOM API ...

  6. [译文]casperjs使用说明-测试

    capserjs自带了一个测试框架,它提供了一个使你能够更容易的测试你的web应用的工具集. 注意: 1.1版本变更 这个测试框架,包括它的所有API,仅能使用在casperjs test子命令下 如 ...

  7. JavaScript 客户端JavaScript之样式表操作(DOM API 提供模块之一)

    层叠样式 表和动态HTML   层叠样式表(CSS)是指定HTML文档或XML文档的表现的标准.     使用CSS和Javascript,可以创建出各种视觉效果,这些效果可以统称为动态HTML(DH ...

  8. ansible api常用模块与参数

    ###ansibleAPI 常用模块 用于读取yaml,json格式的文件 from ansible.parsing.dataloader import DataLoader #用于管理变量的类,包括 ...

  9. [译文]casperjs使用说明-选择器

    casperjs的选择器可以在dom下工作,他既支持css也支持xpath. 下面所有的例子都基于这段html代码: <!doctype html> <html> <he ...

随机推荐

  1. 【FZU2178】礼物分配

    题意 在双胞胎兄弟Eric与R.W的生日会上,他们共收到了N个礼物,生日过后他们决定分配这N个礼物(numv+numw=N).对于每个礼物他们俩有着各自心中的价值vi和wi,他们要求各自分到的礼物数目 ...

  2. flume 转

    http://blog.csdn.net/xiao_jun_0820/article/details/38111305

  3. Java-实体与集合转换

    import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector ...

  4. 825. Friends Of Appropriate Ages有效的好友请求的数量

    [抄题]: Some people will make friend requests. The list of their ages is given and ages[i] is the age ...

  5. vim全局替换命令-乾颐堂

    语法为 :[addr]s/源字符串/目的字符串/[option] 全局替换命令为::%s/源字符串/目的字符串/g [addr] 表示检索范围,省略时表示当前行. 如:“1,20” :表示从第1行到2 ...

  6. 详解Python垃圾回收机制

    http://www.qytang.com/cn/list/28/417.htmhttp://www.qytang.com/cn/list/28/416.htmhttp://ww 引用计数 Pytho ...

  7. [SoapUI] 通过Groovy获取SoapUI当前Project所在的目录

    import com.eviware.soapui.support.GroovyUtils def groovyUtils = new GroovyUtils( context ) def proje ...

  8. HUST软工1501-1503班第2周作业成绩公布

    说明 本次公布的成绩对应的作业为: 第2周个人作业:WordCount编码和测试 如果同学对作业成绩存在异议,在成绩公布的72小时内(截止日期4月26日0点)可以进行申诉,方式如下: 毕博平台的第二周 ...

  9. 兼容低于IE9不支持html5标签的元素的方法

    方法一: <!--[if lt IE9]> <script>    (function() {     if (!      /*@cc_on!@*/     0) retur ...

  10. setoolkit基础

    1.社会工程学攻击 2.快速追踪测试 3.第三方模块 4.升级软件 5.升级配置 6.帮助 99.退出 1.鱼叉式网络钓鱼攻击 2.网页攻击 3.传染媒介式(俗称木马) 4.建立payloaad和li ...