原文网址http://docs.casperjs.org/en/latest/modules/casper.html
ps:原谅我的渣渣英语
1、create()创建一个casper实例
var casper = require('casper').create();
2、Casper.options 设置casper属性
1)clientScripts
Type: Array
Default: []
每一个被加载页面中的所有路径集合
A collection of script filepaths to include in every page loaded.
2)exitOnError
Type: Boolean
Default: true
脚本运行错误,是否exit
Sets if CasperJS must exit when an uncaught error has been thrown by the script.
3)httpStatusHandlers
Type: Object
Default: {}
请求页面返回状态运行JS对象中的方法
A javascript Object containing functions to call when a requested resource has a given HTTP status code. A dedicated sample is provided as an example.
4)logLevel
Type: String
Default: "error"
日志登记
Logging level (see the logging section for more information)
5)onAlert
Type: Function
Default: null
Signature: onAlert(String message)
JS中的alert()被触发时调用该方法
A function to be called when a javascript alert() is triggered
6)onDie
Type: Function
Default: null
当Casper中的die()被调用时调用
Signature: onDie(Object Casper, String message, String status)
A function to be called when Casper#die() is called
7)onError
Type: Function
Default: null
Signature: onError(String msg, Array backtrace)
当error等级的事件发生时调用
A function to be called when an “error” level event occurs
8)onLoadError
Type: Function
Default: null
Signature: onLoadError(Object Casper, String casper.requestUrl, String status)
请求页面不能下载时调用
A function to be called when a requested resource cannot be loaded
9)onPageInitialized
Type: Function
Default: null
Signature: onPageInitialized(Object page)
请求页面初始化完成后调用
A function to be called after WebPage instance has been initialized
10)onResourceReceived
Type: Function
Default: null
Signature: onResourceReceived(Object resource)
作为Phantomjs中WebPage#onResourceReceived() 回调的代理
Proxy method for PhantomJS’ WebPage#onResourceReceived() callback, but the current Casper instance is passed as first argument.
11)onResourceRequested
Type: Function
Default: null
作为Phantomjs中WebPage#onResourceRequested()回调的代理
Proxy method for PhantomJS’ WebPage#onResourceRequested() callback, but the current Casper instance is passed as first argument.
12)onStepComplete
Type: Function
Default: null
Signature: onStepComplete(Object Casper, stepResult)
一个step方法完成时被调用
A function to be executed when a step function execution is finished.
13)onStepTimeout
Type: Function
Default: Function
Signature: onStepTimeout(Integer timeout, Integer stepNum)
一个step方法超时时调用
A function to be executed when a step function execution time exceeds the value of the stepTimeout option, if any has been set.
By default, on timeout the script will exit displaying an error, except in test environment where it will just add a failure to the suite results.
14)onTimeout
Type: Function
Default: Function
Signature: onTimeout(Integer timeout)
操作超时时被调用
A function to be executed when script execution time exceeds the value of the timeout option, if any has been set.
By default, on timeout the script will exit displaying an error, except in test environment where it will just add a failure to the suite results.
15)onWaitTimeout
Type: Function
Default: Function
Signature: onWaitTimeout(Integer timeout)
waitFor*方法超时式调用
A function to be executed when a waitFor* function execution time exceeds the value of the waitTimeout option, if any has been set.
By default, on timeout the script will exit displaying an error, except in test environment where it will just add a failure to the suite results.
16)page
Type: WebPage
Default: null
PhantomJS 网页实例
An existing PhantomJS WebPage instance
17)pageSettings
Type: Object
Default: {}
设置PhantomJS webpage对象:
是否执行script(默认true)
是否加载图片(true)
是否加载NPAPI插件(flash\Sliverlight)(true)
本地资源是否可以上传(false)
定义UserAgent
设置HTTP认证的用户名
设置HTTP认证的密码
是否允许跨域请求(false)
PhantomJS’s WebPage settings object. Available settings are:
javascriptEnabled defines whether to execute the script in the page or not (default to true)
loadImages defines whether to load the inlined images or not
loadPlugins defines whether to load NPAPI plugins (Flash, Silverlight, …) or not
localToRemoteUrlAccessEnabled defines whether local resource (e.g. from file) can access remote URLs or not (default to false)
userAgent defines the user agent sent to server when the web page requests resources
userName sets the user name used for HTTP authentication
password sets the password used for HTTP authentication
XSSAuditingEnabled defines whether load requests should be monitored for cross-site scripting attempts (default to false)
18)remoteScripts(1.0新特性)
Type: Array
Default: []
每一个被加载页面中包含的所有远程链接
A collection of remote script urls to include in every page loaded
19)safeLogs(1.0新特性)
Type: Boolean
Default: true
设置密码是否不以明文显示
When this option is set to true — which is the default, any password information entered in <input type=”password”> will be obfuscated in log messages. Set safeLogs to false to disclose passwords in plain text (not recommended).
20)silentErrors
Type: 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.
21)stepTimeout
Type: Number
Default: null
最大step超时时间(单位毫秒)
Max step timeout in milliseconds; when set, every defined step function will have to execute before this timeout value has been reached. You can define the onStepTimeout() callback to catch such a case. By default, the script will die() with an error message.
22)timeout
Type: Number
Default: null
最大超时时间(单位毫秒)
Max timeout in milliseconds
23)verbose
Type: Boolean
Default: false
实时输出日志信息
Realtime output of log messages
24)viewportSize
Type: Object
Default: null
设置窗口大小
Viewport size, eg. {width: 800, height: 600}
25)retryTimeout
Type: Number
Default: 100
重试时间间隔
Default delay between attempts, for wait* family functions.
26)waitTimeout
Type: Number
Default: 5000
等待时间间隔
Default wait timeout, for wait* family functions.
3、Casper prototype
1)back()
浏览器返回
2) forward().
浏览器前进
3) base64encode(String url [, String method, Object data])
对客户端的XMLHttpRequest按照base64进行编码
Encodes a resource using the base64 algorithm synchronously using client-side XMLHttpRequest.
Example:对google logo 图片编码
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(); });
4)bypass(Numbr nb)(1.1新特性)
指定跳过一定数量的step
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();
5) click(String selector)
点击selector匹配的元素,该方法按照策略尝试两次
1、触发Javascript 的MouseEvent
2、第一次尝试失败,触发QTwebkit事件
Performs a click on the element matching the provided selector expression. The method tries two strategies sequentially:
1、trying to trigger a MouseEvent in Javascript
2、using native QtWebKit event if the previous attempt failed
Example:
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();
6) clickLabel(String label[, String tag])(0.6.1新特性)
点击第一个和label匹配的DOM元素,或者确保该元素是一个标签
Clicks on the first DOM element found containing label text. Optionaly ensures that the element node name is tag:
Example:
// <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'); });
7)capture(String targetFilepath, [Object clipRect, Object imgOptions])
替换PhantomJS’ WebPage#render,增加一个clipRect参数自动设置页面的大小
Proxy method for PhantomJS’ WebPage#render. Adds a clipRect parameter for automatically setting page clipRect setting and reverts it back once done:
Example:
casper.start('http://www.google.fr/', function() { this.capture('google.png', { top: 100, left: 100, width: 500, height: 400 }); }); casper.run();
(1.1新特性)
imgOptions对象有两个选项
1、设置图片格式,避免依赖文件名
2、设置图片的质量(1-100)
The imgOptions object allows to specify two options:
format to set the image format manually, avoiding relying on the filename
quality to set the image quality, from 1 to 100
Example:
casper.start('http://foo', function() { this.capture('foo', undefined, { format: 'jpg', quality: 75 }); });
8)captureBase64(String format[, Mixed area])(0.6.5新特性)
截屏二进制图片,可以使整个屏幕,也可以是部分区域
支持的图片格式有bmp, jpg, jpeg, png, ppm, tiff, xbm and xpm.
截图区域的表示方法:
1、使用字符串,代表一个CSS3 selector
2、使用clipRect,代表一个区域
3、使用一个对象,一个selector对象
Computes the Base64 representation of a binary image capture of the current page, or an area within the page, in a given format.
Supported image formats are bmp, jpg, jpeg, png, ppm, tiff, xbm and xpm.
The area argument can be either of the following types:
1、String: area is a CSS3 selector string, eg. div#plop form[name="form"] input[type="submit"]
2、clipRect: area is a clipRect object, eg. {"top":0,"left":0,"width":320,"height":200}
3、Object: area is a selector object, eg. an XPath selector
Example:
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();
9)captureSelector(String targetFile, String selector [, Object imgOptions])(1.1新特性)
截取指定页面保存到目标文件
Captures the page area containing the provided selector and saves it to targetFile
Example:
casper.start('http://www.weather.com/', function() { this.captureSelector('weather.png', '#wx-main'); }); casper.run();
(1.1新特性)
imgOptions同capture(String targetFilepath, [Object clipRect, Object imgOptions])
10) clear()(0.6.5新特性)
清楚当前环境内容,避免以前加载的DOM仍旧存在
把他当作在远程DOM环境停止Javascript执行的一个方法
Clears the current page execution environment context. Useful to avoid having previously loaded DOM contents being still active.
Think of it as a way to stop javascript execution within the remote DOM environment:
Example:
casper.start('http://www.google.fr/', function() { this.clear(); // javascript execution in this page has been stopped }); casper.then(function() { // ... }); casper.run();
11)debugHTML([String selector, Boolean outer])
在控制台输出getHtml的结果,与gethtml()具有相通的参数列表
Outputs the results of getHTML() directly to the console. It takes the same arguments as getHTML().
12)debugPage()
当前页面的内容标准输出,用来调试
Logs the textual contents of the current page directly to the standard output, for debugging purpose:
Example:
casper.start('http://www.google.fr/', function() { this.debugPage(); }); casper.run();
13)die(String message[, int status])
出现error退出phantom并且设置一个退出状态码
Exits phantom with a logged error message and an optional exit status code:
Example:
casper.start('http://www.google.fr/', function() { this.die("Fail.", 1); }); casper.run();
14)download(String url, String target[, String method, Object data])
保存远程资源到本地文件系统,使用method设置HTTP方法,使用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()):
Example:
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
15)each(Array array, Function fn)
遍历array中的元素,执行一个回溯
Iterates over provided array items and execute a callback:
Example:
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();
Example:
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();
16)eachThen(Array array, Function then)(1.1新特性)
遍历array,增加一个step,用当前的数据处理数组元素
Iterates over provided array items and adds a step to the stack with current data attached to it:
Example :
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();
17)echo(String message[, String style])
控制台输出打印一些东西,stytle设置颜色
Prints something to stdout, optionally with some fancy color (see the colorizer module for more information):
Example:
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();
18)evaluate(Function fn[, arg1[, arg2[, …]]])
基于PhantomJS’ WebPage#evaluate,在当前DOM执行语句
Basically PhantomJS’ WebPage#evaluate equivalent. Evaluates an expression in the current page DOM context:
Example:
casper.evaluate(function(username, password) { document.querySelector('#username').value = username; document.querySelector('#password').value = password; document.querySelector('#submit').click(); }, 'sheldon.cooper', 'b4z1ng4');
注意:如果是填充和提交表单最好使用fill()方法
19)evaluateOrDie(Function fn[, String message])
当前页面的DOM执行语句,如果返回的不是true则执行die()方法
Evaluates an expression within the current page DOM and die() if it returns anything but true:
Example:
casper.start('http://foo.bar/home', function() { this.evaluateOrDie(function() { return /logged in/.match(document.title); }, 'not authenticated'); }); casper.run();
20)exit([int status])
退出phantomJS,返回一个状态码
Exits PhantomJS with an optional exit status code.
21)exists(String selector)
检查DOM中是否有与selector匹配的元素
Checks if any element within remote DOM matches the provided selector:
Example:
casper.start('http://foo.bar/home', function() { if (this.exists('#my_super_id')) { this.echo('found #my_super_id', 'INFO'); } else { this.echo('#my_super_id not found', 'ERROR'); } }); casper.run();
22)fetchText(String selector)
寻找与selector匹配的文本内容,如果有多个匹配的结果,将所有的内容连接起来
Retrieves text contents matching a given selector expression. If you provide one matching more than one element, their textual contents will be concatenated:
Example:
casper.start('http://google.com/search?q=foo', function() { this.echo(this.fetchText('h3')); }).run();
23)log(String message[, String level, String space])
用一个可选的级别和空间记录一条消息,可用的级别有:debug, info, warning and error
命名空间可以过滤你的日志。默认的情况下Casper的日志消息有两个不同的空间:phantom and remote,用以区分日志发生在PhantomJS环境还是远程环境
Logs a message with an optional level in an optional space. Available levels are debug, info, warning and error. A space is a kind of namespace you can set for filtering your logs. By default, Casper logs messages in two distinct spaces: phantom and remote, to distinguish what happens in the PhantomJS environment from the remote one:
24)fill(String selector, Object values[, Boolean submit])
填写表单,确定是否提交,使用他们的name属性
Fills the fields of a form with given values and optionally submits it. Fields are referenced by their name attribute.
(1.1新特性可以使用CSS3或者xpath)
Example:
Html:
<form action="/contact" id="contact-form" enctype="multipart/form-data"> <input type="text" name="subject"/> <textearea name="content"></textearea> <input type="radio" name="civility" value="Mr"/> Mr <input type="radio" name="civility" value="Mrs"/> Mrs <input type="text" name="name"/> <input type="email" name="email"/> <input type="file" name="attachment"/> <input type="checkbox" name="cc"/> Receive a copy <input type="submit"/> </form>
Js:
casper.start('http://some.tld/contact.form', function() { this.fill('form#contact-form', { 'subject': 'I am watching you', 'content': 'So be careful.', 'civility': 'Mr', 'name': 'Chuck Norris', 'email': '[email protected]', 'cc': true, 'attachment': '/Users/chuck/roundhousekick.doc' }, true); }); casper.then(function() { this.evaluateOrDie(function() { return /message sent/.test(document.body.innerText); }, 'sending message failed'); }); casper.run(function() { this.echo('message sent').exit(); });
Fill()支持单选或者多选,多选的选项用数组表示
Example:
html:
<form action="/contact" id="contact-form" enctype="multipart/form-data"> <select multiple name="category"> <option value=?"0">Friends?</option>? <option value=?"1">?Family?</option>? <option value=?"2">?Acquitances?</option>? <option value=?"3">?Colleagues</option>? </select> </form>
Js:
casper.then(function() { this.fill('form#contact-form', { 'categories': ['0', '1'] // Friends and Family }); });
目前fill()方法不能使用xpath填充表单;phantomjs只允许使用css3选择器使用uploadFile()方法
25)fillSelectors(String selector, Object values[, Boolean submit])(1.1新特性)
使用CSS3填充表单,并确定是否提交
Fills form fields with given values and optionally submits it. Fields are referenced by CSS3 selectors:
Example:
casper.start('http://some.tld/contact.form', function() { this.fillSelectors('form#contact-form', { 'input[name="subject"]': 'I am watching you', 'input[name="content"]': 'So be careful.', 'input[name="civility"]': 'Mr', 'input[name="name"]': 'Chuck Norris', 'input[name="email"]': '[email protected]', 'input[name="cc"]': true, 'input[name="attachment"]': '/Users/chuck/roundhousekick.doc' }, true); });
26)fillLabels(String selector, Object values[, Boolean submit])(1.1新特性)
填充表单,使用Label使用label内容表示
fills a form with provided field values using associated label text Fields are referenced by label content values:
Example:
casper.start('http://some.tld/contact.form', function() { this.fillLabels('form#contact-form', { Email: '[email protected]', Password: 'chuck', Content: 'Am watching thou', Check: true, No: true, Topic: 'bar', Multitopic: ['bar', 'car'], File: fpath, "1": true, "3": true, Strange: "very" }, true); });
27)fillXPath(String selector, Object values[, Boolean submit])(1.1新特性)
填充表达,form元素总是使用css3选择器,fields选择xpath选择器
Fills form fields with given values and optionally submits it. While the form element is always referenced by a CSS3 selector, fields are referenced by XPath selectors:
Example:
casper.start('http://some.tld/contact.form', function() { this.fillXPath('form#contact-form', { '//input[@name="subject"]': 'I am watching you', '//input[@name="content"]': 'So be careful.', '//input[@name="civility"]': 'Mr', '//input[@name="name"]': 'Chuck Norris', '//input[@name="email"]': '[email protected]', '//input[@name="cc"]': true, }, true); });
(fillXPath()不可以使用xpath,PhantomJS在uploadFile()时只能使用css3)
28)getCurrentUrl()
获得当前页面URL,这个URL已经被解码
Retrieves current page URL. Note that the url will be url-decoded:
Example:
casper.start('http://www.google.fr/', function() { this.echo(this.getCurrentUrl()); // "http://www.google.fr/" }); casper.run();
29)getElementAttribute(String selector, String attribute)(1.0新特性)
获取与selector和sttribute匹配的第一个元素值
Retrieves the value of an attribute on the first element matching the provided selector:
Example:
var casper = require('casper').create(); casper.start('http://www.google.fr/', function() { require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google" }); casper.run();
30)getElementsAttribute(String selector, String attribute)(1.1新特性)
获取与selector和sttribute匹配的所有元素值
Retrieves the values of an attribute on each element matching the provided selector:
Example:
var casper = require('casper').create(); casper.start('http://www.google.fr/', function() { require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google" });
31) getElementBounds(String selector)
获取与selector匹配的第一个元素的区域,返回top,left,width,heirght ,不存在元素返回null
Retrieves boundaries for a DOM element matching the provided selector.
It returns an Object with four keys: top, left, width and height, or null if the selector doesn’t exist:
Example :
var casper = require('casper').create(); casper.start('http://www.google.fr/', function() { require('utils').dump(this.getElementBounds('div[title="Google"]')); }); casper.run();
输出:
{
"height": 95,
"left": 352,
"top": 16,
"width": 275
}
32)getElementsBounds(String selector)(1.0新特性)
获取与selector匹配的所有元素的区域,返回一个boundary数组
Retrieves a list of boundaries for all DOM elements matching the provided selector.
It returns an array of objects with four keys: top, left, width and height (see getElementBounds()).
33)getElementInfo(String selector)(1.0新特性)
获取与selector匹配的第一个元素的信息
Retrieves information about the first element matching the provided selector:
Example:
casper.start('http://google.fr/', function() { require('utils').dump(this.getElementInfo('#hplogo')); });
输出:
{
"attributes": {
"align": "left",
"dir": "ltr",
"id": "hplogo",
"onload": "window.lol&&lol()",
"style": "height:110px;width:276px;background:url(/images/srpr/logo1w.png) no-repeat",
"title": "Google"
},
"height": 110,
"html": "<div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div>",
"nodeName": "div",
"tag": "<div dir=\"ltr\" title=\"Google\" align=\"left\" id=\"hplogo\" onload=\"window.lol&&lol()\" style=\"height:110px;width:276px;background:url(/images/srpr/logo1w.png) no-repeat\"><div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div></div>",
"text": "France\n",
"visible": true,
"width": 276,
"x": 62,
"y": 76
}
34)getElementsInfo(String selector)(1.0新特性)
获取与selector匹配的所有元素的信息
Retrieves information about all elements matching the provided selector:
35)getFormValues(String selector)(1.0新特性)
获取与selector匹配的表单的所有值
Retrieves a given form all of its field values:
Example:
casper.start('http://www.google.fr/', function() { this.fill('form', {q: 'plop'}, false); this.echo(this.getFormValues('form').q); // 'plop' }); casper.run();
36)getGlobal(String name)
通过名字获取远程DOM环境下的一个全局变量的值,通常getGlobal(‘foo‘) 返回window.foo
Retrieves a global variable value within the remote DOM environment by its name. Basically, getGlobal(‘foo‘) will retrieve the value of window.foo from the page:
Example:
casper.start('http://www.google.fr/', function() { this.echo(this.getGlobal('innerWidth')); // 1024 }); casper.run();
37)getHTML([String selector, Boolean outer])(1.0新特性)
获取当前页面的html代码,默认情况下输出整个页面的html内容,匹配selecotr输出页面内指定内容
Retrieves HTML code from the current page. By default, it outputs the whole page HTML contents:
Example:
casper.start('http://www.google.fr/', function() { this.echo(this.getHTML()); }); casper.run();
输出:
<html> <body> <h1 id="foobar">Plop</h1> </body> </html>
Example:
casper.start('http://www.site.tld/', function() { this.echo(this.getHTML('h1#foobar')); // => 'Plop' });
38)getPageContent()(1.0新特性)
获取当前页面内容,使用除了HTML外的其他文件类型处理
Retrieves current page contents, dealing with exotic other content types than HTML:
Example:
var casper = require('casper').create(); casper.start().then(function() { this.open('http://search.twitter.com/search.json?q=casperjs', { method: 'get', headers: { 'Accept': 'application/json' } }); }); casper.run(function() { require('utils').dump(JSON.parse(this.getPageContent())); this.exit(); });
39)getTitle()
获取当前页面的title
Retrieves current page title:
Example :
casper.start('http://www.google.fr/', function() { this.echo(this.getTitle()); // "Google" }); casper.run();
40)mouseEvent(String type, String selector)(0.6.9新特性)
根据selector匹配一个元素,触发鼠标事件,支持的事件有: mouseup, mousedown, click, mousemove, mouseover and mouseout
Triggers a mouse event on the first element found matching the provided selector.
Supported events are mouseup, mousedown, click, mousemove, mouseover and mouseout:
Example:
casper.start('http://www.google.fr/', function() { this.mouseEvent('click', 'h2 a'); }); casper.run();
41)open(String location, Object Settings)
执行一个HTTP请求,打开所给的链接,支持的请求方式:GET, POST, PUT, DELETE and HEAD requests.
Performs an HTTP request for opening a given location. You can forge GET, POST, PUT, DELETE and HEAD requests.
Example for a standard GET request:
asper.start(); casper.open('http://www.google.com/').then(function() { this.echo('GOT it.'); }); casper.run(); Example for a POST request: casper.start(); casper.open('http://some.testserver.com/post.php', { method: 'post', data: { 'title': 'Plop', 'body': 'Wow.' } }); casper.then(function() { this.echo('POSTED it.'); }); casper.run();
To pass nested parameters arrays:
casper.open('http://some.testserver.com/post.php', { method: 'post', data: { 'standard_param': 'foo', 'nested_param[]': [ // please note the use of square brackets! 'Something', 'Something else' ] } });
(1.0新特性,自定义headers)
casper.open('http://some.testserver.com/post.php', { method: 'post', data: { 'title': 'Plop', 'body': 'Wow.' }, headers: { 'Accept-Language': 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3' } });
42)reload([Function then])(1.0新特性)
重新加载当前页面
Reloads current page location:
Example:
casper.start('http://google.com', function() { this.echo("loaded"); this.reload(function() { this.echo("loaded again"); }); }); casper.run();
43)repeat(int times, Function then)
重复当前的步骤times次
Repeats a navigation step a given number of times:
Example:
casper.start().repeat(3, function() { this.echo("Badger"); }); casper.run();
44)resourceExists(String|Function|RegExp test)
检查资源是否被加载,可以使用a function, a string or a RegExp测试
Checks if a resource has been loaded. You can pass either a function, a string or a RegExp instance to perform the test:
Example:
casper.start('http://www.google.com/', function() { if (this.resourceExists('logo3w.png')) { this.echo('Google logo loaded'); } else { this.echo('Google logo not loaded', 'ERROR'); } }); casper.run();
45)run(fn onComplete[, int time])
运行整个测试,测试完成后执行一个回调,这个方法是为了执行Casper导航
Runs the whole suite of steps and optionally executes a callback when they’ve all been done. Obviously, calling this method is mandatory in order to run the Casper navigation suite.
Example:
casper.start('http://foo.bar/home', function() { // ... }); // hey, it's missing .run() here! casper.start('http://foo.bar/home', function() { // ... }); casper.run();
该方法仍然可以支持一个onComplete的回调,可以把它当作自定义方法的最后一步,不要忘记了执行exit().
Example :
casper.start('http://foo.bar/home', function() { // ... }); casper.then(function() { // ... }); casper.run(function() { this.echo('So the whole suite ended.'); this.exit(); // <--- don't forget me! }); Example : casper.start('http://foo.bar/home', function() { // ... }); casper.then(function() { // ... }); casper.run(function() { this.echo('So the whole suite ended.'); this.exit(); // <--- don't forget me! });
46)scrollTo(Number x, Number y)(1.1-beta3新特性)
滚动当前文档到指定的坐标(x,y)
Scrolls current document to the coordinates defined by the value of x and y:
Example :
casper.start('http://foo.bar/home', function() { this.scrollTo(500, 300); });
47)scrollToBottom()(1.1-beta3新特性)
滚动当前页面到底部
Scrolls current document to its bottom:
Example:
casper.start('http://foo.bar/home', function() { this.scrollToBottom(); });
48)sendKeys(Selector selector, String keys[, Object options])(1.0新特性)
向与selector匹配的第一个元素发送键盘事件
Sends native keyboard events to the element matching the provided selector:
Example:
casper.then(function() { this.sendKeys('form.contact input#name', 'Duke'); this.sendKeys('form.contact textarea#message', "Damn, I'm looking good."); this.click('form.contact input[type="submit"]'); });
(1.1新特性)
当前支持的元素有: <input>, <textarea>,其他属性contenteditable="true"的元素
Options:
1、
(Boolean) reset:( 1.1-beta3.新特性)
设置为true,先清空当前元素在输入,默认为false,通过使用sendKeys()在后面添加
When set to true, this option will first empty the current field value. By default, it’s set to false and sendKeys() will just append string to the current field value.
2、(Boolean) keepFocus:
想保持焦点使用设置为true
sendKeys() by default will remove the focus on text input fields, which will typically close autocomplete widgets. If you want to maintain focus, use the keepFocus option. For example, if using jQuery-UI, you can click on the first autocomplete suggestion using:
Example :
casper.then(function() { this.sendKeys('form.contact input#name', 'action', {keepFocus: true}); this.click('form.contact ul.ui-autocomplete li.ui-menu-item:first- child a'); });
3、(String) modifiers:
sendKeys() accepts a modifiers option to support key modifiers. The options is a string representing the composition of modifiers to use, separated by the + character:
Example:
casper.then(function() { this.sendKeys('document', 's', {modifiers: 'ctrl+alt+shift'}); });
49)setHttpAuth(String username, String password)
设置HTTP_AUTH_USER and HTTP_AUTH_PW,HHTP认证
Sets HTTP_AUTH_USER and HTTP_AUTH_PW values for HTTP based authentication systems:
Example:
casper.start(); casper.setHttpAuth('sheldon.cooper', 'b4z1ng4'); casper.thenOpen('http://password-protected.domain.tld/', function() { this.echo("I'm in. Bazinga."); }) casper.run();
50)start(String url[, Function then])
Casper开始,通过then参数打开URL,增加后续步骤
Configures and starts Casper, then opens the provided url and optionally adds the step provided by the then argument:
Example:
casper.start('http://google.fr/', function() { this.echo("I'm loaded."); }); casper.run();
Else :
casper.start('http://google.fr/'); casper.then(function() { this.echo("I'm loaded."); }); casper.run();
Or :
casper.start('http://google.fr/'); casper.then(function() { casper.echo("I'm loaded."); }); casper.run();
51)status(Boolean asString)(1.0新特性)
返回当前casper实例的状态
Returns the status of current Casper instance:
Example:
casper.start('http://google.fr/', function() { this.echo(this.status(true)); }); casper.run();
52)then(Function then)
通过提供一个方法,增加一个步骤
This method is the standard way to add a new navigation step to the stack, by providing a simple function:
Example:
casper.start('http://google.fr/'); casper.then(function() { this.echo("I'm in your google."); }); casper.then(function() { this.echo('Now, let me write something'); }); casper.then(function() { this.echo('Oh well.'); }); casper.run();
(1.0新特性)
通过使用回调的第一个参数,可以得到当前HTTP响应的对象
Example:
casper.start('http://www.google.fr/', function(response) { require('utils').dump(response); });
output:
$ casperjs dump-headers.js
{
"contentType": "text/html; charset=UTF-8",
"headers": [
{
"name": "Date",
"value": "Thu, 18 Oct 2012 08:17:29 GMT"
},
{
"name": "Expires",
"value": "-1"
},
// ... lots of other headers
],
"id": 1,
"redirectURL": null,
"stage": "end",
"status": 200,
"statusText": "OK",
"time": "2012-10-18T08:17:37.068Z",
"url": "http://www.google.fr/"
}
获得headers
Example :
casper.start('http://www.google.fr/', function(response) { this.echo(response.headers.get('Date')); });
Output:
Thu, 18 Oct 2012 08:26:34 GMT
52)thenBypass(Number nb)(1.1新特性)
跳过指定数量的step
Adds a navigation step which will bypass a given number of following steps:
Example :
casper.start('http://foo.bar/'); casper.thenBypass(2); casper.then(function() { // This test won't be executed }); casper.then(function() { // Nor this one }); casper.then(function() { // While this one will }); casper.run();
52)thenBypassIf(Mixed condition, Number nb)(1.1新特性)
Condition为true或者函数返回为true,跳过指定数量的step
Bypass a given number of navigation steps if the provided condition is truthy or is a function that returns a truthy value:
Example:
var universe = { answer: 42 }; casper.start('http://foo.bar/'); casper.thenBypassIf(function() { return universe && universe.answer === 42; }, 2); casper.then(function() { // This step won't be executed as universe.answer is 42 }); casper.then(function() { // Nor this one }); casper.then(function() { // While this one will }); casper.run();
53)thenBypassUnless()
Signature: thenBypassUnless(Mixed condition, Number nb)(1.1新特性)
与henBypassIf相反
Opposite of thenBypassIf().
54)thenClick(String selector[, Function then])
增加一个step点击与selector匹配的元素,可以设定一个函数执行
Adds a new navigation step to click a given selector and optionally add a new navigation step in a single operation:
Example:
// Click the first link in the casperJS page casper.start('http://casperjs.org/').thenClick('a', function() { this.echo("I clicked on first link found, the page is now loaded."); }); casper.run();
55)thenEvaluate(Function fn[, arg1[, arg2[, …]]])
增加一个step,执行函数
Adds a new navigation step to perform code evaluation within the current retrieved page DOM:
Example:
casper.start('http://google.fr/').thenEvaluate(function(term) { document.querySelector('input[name="q"]').setAttribute('value', term); document.querySelector('form[name="f"]').submit(); }, 'Chuck Norris'); casper.run();
(同时调用then()和evaluate())
56)thenOpen(String location[, mixed options])
打开一个新的页面,加载完成前,下一步不会执行
Adds a new navigation step for opening a new location, and optionally add a next step when its loaded:
Example:
casper.start('http://google.fr/').then(function() { this.echo("I'm in your google."); }); casper.thenOpen('http://yahoo.fr/', function() { this.echo("Now I'm in your yahoo.") }); casper.run();
thenOPen()也可以设置请求Headers(1.1新特性)
57)thenOpenAndEvaluate(String location[, Function then[, arg1[, arg2[, …]]])
打开一个新网页,执行一段代码
Basically a shortcut for opening an url and evaluate code against remote DOM environment:
Example:
casper.start('http://google.fr/').then(function() { this.echo("I'm in your google."); }); casper.thenOpenAndEvaluate('http://yahoo.fr/', function() { var f = document.querySelector('form'); f.querySelector('input[name=q]').value = 'chuck norris'; f.submit(); }); casper.run(function() { this.debugPage(); this.exit(); });
58)toString()(1.0新特性)
返回当前casper实例的字符串
Returns a string representation of current Casper instance:
Example:
casper.start('http://google.fr/', function() { this.echo(this); // [object Casper], currently at http://google.fr/ }); casper.run();
59)unwait()(1.1新特性)
中端所有正在等待的进程,如果有的话
Abort all current waiting processes, if any.
60)userAgent(String agent)(1.0新特性)
设置USer-agent
Sets the User-Agent string to send through headers when performing requests:
casper.start(); casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)'); casper.thenOpen('http://google.com/', function() { this.echo("I'm a Mac."); this.userAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)'); }); casper.thenOpen('http://google.com/', function() { this.echo("I'm a PC."); }); casper.run();
61)viewport(Number width, Number height[, Function then])
改变当前窗口大小
Changes current viewport size:
Example:
casper.viewport(1024, 768);
(1.1新特性)可以把viewport()作为一个step
Example :
casper.viewport(1024, 768, function() { // new view port is effective }); Equal: casper.viewport(1024, 768).then(function() { // new view port is now effective });
62)visible(String selector)
检查selector匹配的元素在远程页面是否可见
Checks if the DOM element matching the provided selector expression is visible in remote page:
Example:
casper.start('http://google.com/', function() { if (this.visible('#hplogo')) { this.echo("I can see the logo"); } else { this.echo("I can't see the logo"); } });
63)wait(Number timeout[, Function then])
使当前步骤等待timeout毫秒
Pause steps suite execution for a given amount of time, and optionally execute a step on done:
Example:
casper.start('http://yoursite.tld/', function() { this.wait(1000, function() { this.echo("I've waited for a second."); }); }); casper.run();
equal:
casper.start('http://yoursite.tld/'); casper.wait(1000, function() { this.echo("I've waited for a second."); }); casper.run();
63)waitFor(Function testFx[, Function then, Function onTimeout, Number timeout, Object details])
等待,直到一个方法fanhui true,继续下一步
可以使用ontimeout设置等待超时时间,如果超时,则进行回调,使用timeout设置超时退出时间,超时退出,默认退出超时5000ms
Waits until a function returns true to process any next step.
You can also set a callback on timeout using the onTimeout argument, and set the timeout using the timeout one, in milliseconds. The default timeout is set to 5000ms:
Example :
casper.start('http://yoursite.tld/'); casper.waitFor(function check() { return this.evaluate(function() { return document.querySelectorAll('ul.your-list li').length > 2; }); }, function then() { this.captureSelector('yoursitelist.png', 'ul.your-list'); }); casper.run();
Example :
c
asper.start('http://yoursite.tld/'); casper.waitFor(function check() { return this.evaluate(function() { return document.querySelectorAll('ul.your-list li').length > 2; }); }, function then() { // step to execute when check() is ok this.captureSelector('yoursitelist.png', 'ul.your-list'); }, function timeout() { // step to execute if check has failed this.echo("I can't haz my screenshot.").exit(); }); casper.run();
64)waitForAlert(Function then[, Function onTimeout, Number timeout])(1.1-beta4新特性)[官网下载的是beta3,不知为啥来了个beta4新特性,匪夷所思]
等待,知道javascript 的alert 时间被触发,将alert的消息传递到response.data里
Waits until a JavaScript alert is triggered. The step function will be passed the alert message in the response.data property:
Example:
casper.waitForAlert(function(response) { this.echo("Alert received: " + response.data); });
65)waitForPopup(String|RegExp urlPattern[, Function then, Function onTimeout, Number timeout])(1.0新特性)
等待,知道一个popup被加载打开
Waits for a popup having its url matching the provided pattern to be opened and loaded.
The currently loaded popups are available in the Casper.popups array-like property:
Example:
casper.start('http://foo.bar/').then(function() { this.test.assertTitle('Main page title'); this.clickLabel('Open me a popup'); }); // this will wait for the popup to be opened and loaded casper.waitForPopup(/popup\.html$/, function() { this.test.assertEquals(this.popups.length, 1); }); // this will set the popup DOM as the main active one only for time the // step closure being executed casper.withPopup(/popup\.html$/, function() { this.test.assertTitle('Popup title'); }); // next step will automatically revert the current page to the initial one casper.then(function() { this.test.assertTitle('Main page title'); });
66)waitForResource(String|Function|RegExp testFx[, Function then, Function onTimeout, Number timeout])
等待,知道资源出现,资源匹配方式可以是string,function,RegExp
Wait until a resource that matches a resource matching constraints defined by testFx are satisfied to process a next step.
The testFx argument can be either a string, a function or a RegExp instance:
Example :
casper.waitForResource("foobar.png", function() { this.echo('foobar.png has been loaded.'); }); casper.waitForResource(/foo(bar|baz)\.png$/, function() { this.echo('foobar.png or foobaz.png has been loaded.'); }); casper.waitForResource(function testResource(resource) { return resource.url.indexOf("https") === 0; }, function onReceived() { this.echo('a secure resource has been loaded.'); });
67)waitForUrl(String|RegExp url[, Function then, Function onTimeout, Number timeout])(1.1新特性)
等待,直到当前页面的url和提供的参数匹配(string、RegExp)
Waits for the current page url to match the provided argument (String or RegExp):
Example :
casper.start('http://foo/').waitForUrl(/login\.html$/, function() { this.echo('redirected to login.html'); }); casper.run();
68)waitForSelector(String selector[, Function then, Function onTimeout, Number timeout])
等待,知道出现与selector匹配的元素
Waits until an element matching the provided selector expression exists in remote DOM to process any next step. Uses waitFor():
Example:
casper.start('https://twitter.com/#!/n1k0'); casper.waitForSelector('.tweet-row', function() { this.captureSelector('twitter.png', 'html'); }); casper.run();
69)waitWhileSelector(String selector[, Function then, Function onTimeout, Number timeout])
等待,直到selector匹配的元素不存在
Waits until an element matching the provided selector expression does not exist in remote DOM to process a next step. Uses waitFor():
Example:
casper.start('http://foo.bar/'); casper.waitWhileSelector('.selector', function() { this.echo('.selector is no more!'); }); casper.run();
70)waitForSelectorTextChange(String selectors[, Function then, Function onTimeout, Number timeout])
等待,直到selector匹配的元素的文本改变
Waits until the text on an element matching the provided selector expression is changed to a different value before processing the next step.
Example:
casper.start('http://foo.bar/'); casper.waitForSelectorTextChange('.selector', function() { this.echo('The text on .selector has been changed.'); }); casper.run();
71)waitForText(String text[, Function then, Function onTimeout, Number timeout])(1.0新特性)
等待,直到text传入的值已经包含在当前文本中
Waits until the passed text is present in the page contents before processing the immediate next step. Uses waitFor():
Example:
casper.start('http://why.univer.se/').waitForText("42", function() { this.echo('Found the answer.'); }); casper.run();
72)waitUntilVisible(String selector[, Function then, Function onTimeout, Number timeout])
等待,直到selector匹配的元素不可见
Waits until an element matching the provided selector expression is visible in the remote DOM to process a next step. Uses waitFor().
73)waitWhileVisible(String selector[, Function then, Function onTimeout, Number timeout])
等待,知道selector匹配的元素可见
Waits until an element matching the provided selector expression is no longer visible in remote DOM to process a next step. Uses waitFor().
74)warn(String message)
记录日志,打印warnning message
Logs and prints a warning message to the standard output:
Example :
casper.warn("I'm a warning message.");
75)withFrame(String|Number frameInfo, Function then)(1.0新特性)
根据传入的name和index参数值,将主页转换到frame,执行下一步
该步骤持续一直到转换完
Switches the main page to the frame having the name or frame index number matching the passed argument, and processes a step.
The page context switch only lasts until the step execution is finished:
Example:
casper.start('tests/site/frames.html', function() { this.test.assertTitle('FRAMESET TITLE'); }); casper.withFrame('frame1', function() { this.test.assertTitle('FRAME TITLE'); }); casper.withFrame(0, function() { this.test.assertTitle('FRAME TITLE'); }); casper.then(function() { this.test.assertTitle('FRAMESET TITLE'); });
76)withPopup(Mixed popupInfo, Function then)(1.0新特性)
根据传入的参数,从主页转换到弹出的页面,执行下一步,该步骤持续知道转换完成
Switches the main page to a popup matching the information passed as argument, and processes a step. The page context switch only lasts until the step execution is finished:
Example:
casper.start('http://foo.bar/').then(function() { this.test.assertTitle('Main page title'); this.clickLabel('Open me a popup'); }); // this will wait for the popup to be opened and loaded casper.waitForPopup(/popup\.html$/, function() { this.test.assertEquals(this.popups.length, 1); }); // this will set the popup DOM as the main active one only for time the // step closure being executed casper.withPopup(/popup\.html$/, function() { this.test.assertTitle('Popup title'); }); // next step will automatically revert the current page to the initial one casper.then(function() { this.test.assertTitle('Main page title'); });
78)zoom(Number factor)(1.0新特性)
设置当前页面的缩放因子
Sets the current page zoom factor:
Example:
var casper = require('casper').create(); casper.start().zoom(2).thenOpen('http://google.com', function() { this.capture('big-google.png'); }); casper.run();
原文网址http://docs.casperjs.org/en/latest/modules/casper.html