capserjs-prototype(下)

scrollTo()

具体样式: scrollTo(Number x, Number y)
New in version 1.1-beta3.
Scrolls current document to the coordinates defined by the value of x and y:
当前文档去滑动到被设定的x轴和y轴的坐标轴

casper.start('http://foo.bar/home', function() {
    this.scrollTo(500, 300);
});

Note
This operation is synchronous.
*
笔记
这个操作是同步的.
*

scrollToBottom()

具体样式: scrollToBottom()
New in version 1.1-beta3.
Scrolls current document to its bottom:
滑动当前文档到它的按钮:

casper.start('http://foo.bar/home', function() {
    this.scrollToBottom();
});

Note
This operation is synchronous.
*
*
笔记
这个操作是同步的
*

sendKeys()

具体样式: sendKeys(Selector selector, String keys[, Object options])
New in version 1.0.
Sends native keyboard events to the element matching the provided selector:
发送一个原生的键盘时间到给定的选择器匹配的元素:

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

New in version 1.1.
The currently supported HTMLElements that can receive keyboard events from sendKeys are <input>, &lttextarea>, and any HTMLElement with attribute contenteditable="true".
当前支持的HTML元素能从发送键接受键盘的事件是input,textarea,并且任何的可编辑属性contenteditable=true的html元素
Options
可选项

(Boolean) reset:
New in version 1.1-beta3.
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.
当设置为true时,这个选项就会首相设置空当前的字段值.默认,将会设置为false并且sendKeys方法将会插入一个字符串到当前字段值.

(Boolean) keepFocus:
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:

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

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

casper.then(function() {
    this.sendKeys('document', 's', {modifiers: 'ctrl+alt+shift'});
});

Available modifiers are:
可编辑的是:
ctrl
alt
shift
meta
keypad

setHttpAuth()

具体样式: setHttpAuth(String username, String password)
Sets HTTP_AUTH_USER and HTTP_AUTH_PW values for HTTP based authentication systems:
设置HTTP_AUTH_USER和HTTP_AUTH_PW为http基础权限系统

casper.start();
casper.setHttpAuth('sheldon.cooper', 'b4z1ng4');
casper.thenOpen('http://password-protected.domain.tld/', function() {
    this.echo("I'm in. Bazinga.");
})
casper.run();

Of course you can directly pass the auth string in the url to open:
当然你也可以直接传入权限字符串在URL中去打开

var url = 'http://sheldon.cooper:b4z1ng4@password-protected.domain.tld/';
casper.start(url, function() {
    this.echo("I'm in. Bazinga.");
})
casper.run();

start()

具体样式: start(String url[, Function then])
Configures and starts Casper, then opens the provided url and optionally adds the step provided by the then argument:
配置并且开始casper,然后打开给定的url然后根据参数添加步骤.

casper.start('http://google.fr/', function() {
    this.echo("I'm loaded.");
});
casper.run();

Alternatively:
要注意的是:

casper.start('http://google.fr/');
casper.then(function() {
    this.echo("I'm loaded.");
});
casper.run();

Or alternatively:
另外要注意是:

casper.start('http://google.fr/');
casper.then(function() {
    casper.echo("I'm loaded.");
});
casper.run();

Matter of taste!
品味问题!

Note
You must call the start() method in order to be able to add navigation steps and run the suite. If you don’t you’ll get an error message inviting you to do so anyway.
*
*
笔记
你必须调用start方法,为的是去添加一个导航步骤然后运行套件.如果你没有,你将会或得到一个邀请你无论如何这么做的错误消息
*

status()

具体样式: status(Boolean asString)
New in version 1.0.
Returns the status of current Casper instance:
返回当前casper实例的状态

casper.start('http://google.fr/', function() {
    this.echo(this.status(true));
});
casper.run();

then()

具体样式: then(Function then)
This method is the standard way to add a new navigation step to the stack, by providing a simple function:
这个方法是去添加一个新的导航步骤去堆叠的基础步骤,下面给出的一个简单的功能:

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

You can add as many steps as you need. Note that the current Casper instance automatically binds the this keyword for you within step functions.
你能够添加一些列你需要的步骤.要注意的是,当前casper实例自动绑定这些关键词,用户步骤功能.
To run all the steps you defined, call the run() method, and voila.
取运行所有的你定义步骤,调用run方法,然后瞧

Note
You must start() the casper instance in order to use the then() method.
*
*
为了去使用then方法,你必须运行casper实例的start()方法
*

Accessing the current HTTP response
获取当前http的状态码
New in version 1.0.
You can access the current HTTP response object using the first parameter of your step callback:
你能够使用第一个回调的参数response,获取当前的http状态码的返回对象

casper.start('http://www.google.fr/', function(response) {
    require('utils').dump(response);
});

That gives:
如下给出:

$ 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/"
}

So to fetch a particular header by its name:
所以通过它们的名字去获取特殊的header:

casper.start('http://www.google.fr/', function(response) {
    this.echo(response.headers.get('Date'));
});

That gives:
如下给出:

$ casperjs dump-headers.js
Thu, 18 Oct 2012 08:26:34 GMT

Warning
Step functions added to then() are processed in two different cases:
*
*
警告
步骤功能以两种不同方式,添加到then方法被处理
*

when the previous step function has been executed,
当之前的步骤功能已经被执行,
when the previous main HTTP request has been executed and the page loaded;
当之前的主要的http请求已经被执行并且页面载入完成.
Note that there’s no single definition of page loaded; is it when the DOMReady event has been triggered? Is it “all requests being finished”? 注意页面载入没有一个单一的定义;当DOMReady时间已经被触发?当所有请求完成?
Is it *all application logic being performed”? Or “all elements being rendered”? The answer always depends on the context.

所有应用逻辑被执行?又或者所有元素被渲染?这些答案经常依赖上下文.
Hence why you’re encouraged to always use the waitFor() family methods to keep explicit control on what you actually expect.
所以,你被鼓励去惊颤使用waitFor类似的方法去为你实际的预测保持明确的控制
A common trick is to use waitForSelector():
一个土场的技巧是使用waitForSelector():

casper.start('http://my.website.com/');
casper.waitForSelector("#plop", function() {
    this.echo("I'm sure #plop is available in the DOM");
});
casper.run();

thenBypass()

具体样式: thenBypass(Number nb)
New in version 1.1.
Adds a navigation step which will bypass a given number of following steps:
添加一个会跳过给定跟随的数字导航步骤

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

thenBypassIf()

具体样式: thenBypassIf(Mixed condition, Number nb)
New in version 1.1.
Bypass a given number of navigation steps if the provided condition is truthy or is a function that returns a truthy value:
跳过一个给定的导航步骤如果给定的情况真的,否则是返回真相的一个函数

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

thenBypassUnless()

具体样式: thenBypassUnless(Mixed condition, Number nb)
New in version 1.1.
Opposite of thenBypassIf().
thenBypassIf的对立面

thenClick()

具体样式: thenClick(String selector[, Function then])
Adds a new navigation step to click a given selector and optionally add a new navigation step in a single operation:
添加一个导航步骤去点击给定的选择器并且可选的在一个单独的处理中添加一个当行步骤

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

This method is basically a convenient a shortcut for chaining a then() and an click() calls.
对于then()和click(),这个方法是连接的一个方便一个快捷的方式.

thenEvaluate()

具体样式: thenEvaluate(Function fn[, arg1[, arg2[, …]]])
Adds a new navigation step to perform code evaluation within the current retrieved page DOM:
添加一个导航步骤用获取的页面DOM去验证代码执行

// Querying for "Chuck Norris" on Google
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();

This method is a convenient shortcut for chaining then() and evaluate() calls.
这个方法是then()和evaluate()调用的快捷调用方式.

thenOpen()

具体样式: thenOpen(String location[, mixed options])
Adds a new navigation step for opening a new location, and optionally add a next step when its loaded:
添加一个导航步骤去打开一个新连接,并且可选的添加一个导航步骤当它载入后.

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

New in version 1.0.
You can also specify request settings by passing a setting object (see open()) as the second argument:
你也可以指定请求设置通过传入一个设置数据,(看oppen方法)作为第二个参数.

casper.start().thenOpen('http://url.to/some/uri', {
    method: "post",
    data: {
        username: 'chuck',
        password: 'n0rr15'
    }
}, function() {
    this.echo("POST request has been sent.")
});
casper.run();

thenOpenAndEvaluate()

具体样式: thenOpenAndEvaluate(String location[, Function then[, arg1[, arg2[, …]]])
Basically a shortcut for opening an url and evaluate code against remote DOM environment:
去打开链接然后执行代码在远程dom环境的基础的快捷方法

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

toString()

具体样式: toString()
New in version 1.0.
Returns a string representation of current Casper instance:
返回当前casper实例的一个代表性的字符串

casper.start('http://google.fr/', function() {
    this.echo(this); // [object Casper], currently at http://google.fr/
});
casper.run();

unwait()

具体样式: unwait()
New in version 1.1.
Abort all current waiting processes, if any.
如有有的话,阻止所有的等待程序

userAgent()

具体样式: userAgent(String agent)
New in version 1.0.
Sets the User-Agent string to send through headers when performing requests:
当执行一个请求时,通过headers设置发送的ua字符串

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

viewport()

具体样式: viewport(Number width, Number height[, Function then])
Changes current viewport size:
改变当前可视的尺寸

casper.viewport(1024, 768);

To be sure page reflowing has occured, you have to use it asynchronously:
确认页面回流已经发生,你不得不使用同步

casper.viewport(1024, 768).then(function() {
    // new view port is now effective
});

New in version 1.1.
As of 1.1 you can pass a then step function directly to viewport():
作为1.1版本你能够传入一个之后的步骤功能给viewport方法

casper.viewport(1024, 768, function() {
    // new view port is effective
});

Note
PhantomJS comes with a default viewport size of 400x300, and CasperJS doesn’t override it by default.
*
*
笔记
phantomjs实现了默认的400x300可视窗,并且casperjs不能够重写他的默认.
*

visible()

具体样式: visible(String selector)
Checks if the DOM element matching the provided selector expression is visible in remote page:
检查是否给定的选择器的表达式是否在远程页面的dom中可视:

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

wait()

具体样式: wait(Number timeout[, Function then])
Pause steps suite execution for a given amount of time, and optionally execute a step on done:
根据给出的时间,暂停步骤套件,并且可选在完成时的执行步骤:

casper.start('http://yoursite.tld/', function() {
    this.wait(1000, function() {
        this.echo("I've waited for a second.");
    });
});
casper.run();

You can also write the same thing like this:
你也可以写相同的事情如下:

casper.start('http://yoursite.tld/');
casper.wait(1000, function() {
    this.echo("I've waited for a second.");
});
casper.run();

waitFor()

具体样式: waitFor(Function testFx[, Function then, Function onTimeout, Number timeout, Object details])
Waits until a function returns true to process any next step.
等到一个函数返回true,才去执行下一步
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:
你也可以设置一个回调,使用onTimeout参数,并且设置超时使用毫秒.默认时间是5000毫秒:

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 using the onTimeout callback:
使用onTimeout回调的例子:

casper.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();

details is a property bag of various information that will be passed to the waitFor.timeout event, if it is emitted. This can be used for better error messages or to conditionally ignore some timeout events.
细节是不同信息将会传给waitfor的属性包.timeout,event,如果被发出.这个可以为更好地错误提醒,或者有条件的湖绿一些超时事件.
Please note, that all waitFor methods are not chainable. Consider wrapping each of them in a casper.then in order to acheive this functionality.
请做笔记,所有的waitFor方法不能够证明.在casper中思考包装每一个项目,为的是理解这个功能.

waitForAlert()

具体样式: waitForAlert(Function then[, Function onTimeout, Number timeout])
New in version 1.1-beta4.
Waits until a JavaScript alert is triggered. The step function will be passed the alert message in the response.data property:
等待知道javascript的alert方法被触发.这个步骤函数在response.data属性中将会被传入弹出的信息

casper.waitForAlert(function(response) {
    this.echo("Alert received: " + response.data);
});

waitForPopup()

具体样式: waitForPopup(String|RegExp urlPattern[, Function then, Function onTimeout, Number timeout])
New in version 1.0.
Waits for a popup having its url matching the provided pattern to be opened and loaded.
等待已经匹配的模式url弹出层被打开,然后载入.
The currently loaded popups are available in the Casper.popups array-like property:
当前载入的弹出层在Casper.popups像数组属性是可选的.

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

waitForResource()

具体样式: waitForResource(String|Function|RegExp testFx[, Function then, Function onTimeout, Number timeout])
Wait until a resource that matches a resource matching constraints defined by testFx are satisfied to process a next step.
等待一个被包含定义的testFx是别的匹配的资源,然后去执行下一步
The testFx argument can be either a string, a function or a RegExp instance:
testFx参数可以是字符串,可以使方法,可以是一个正则实例:

casper.waitForResource("foobar.png", function() {
    this.echo('foobar.png has been loaded.');
});

Using a regexp:
正则:

casper.waitForResource(/foo(bar|baz)\.png$/, function() {
    this.echo('foobar.png or foobaz.png has been loaded.');
});

Using a function:
方法:

casper.waitForResource(function testResource(resource) {
    return resource.url.indexOf("https") === 0;
}, function onReceived() {
    this.echo('a secure resource has been loaded.');
});

waitForUrl()

具体样式: waitForUrl(String|RegExp url[, Function then, Function onTimeout, Number timeout])
New in version 1.1.
Waits for the current page url to match the provided argument (String or RegExp):
等待当前页面的url和给定的参数匹配(字符串或者正则)

casper.start('http://foo/').waitForUrl(/login\.html$/, function() {
    this.echo('redirected to login.html');
});
casper.run();

waitForSelector()

具体样式: waitForSelector(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression exists in remote DOM to process any next step. Uses waitFor():
等待一个元素能够和远程DOM给定的选择器表达式匹配,然后去执行下一步.使用waitFor():

casper.start('https://twitter.com/#!/n1k0');
casper.waitForSelector('.tweet-row', function() {
    this.captureSelector('twitter.png', 'html');
});
casper.run();

waitWhileSelector()

具体样式: waitWhileSelector(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression does not exist in remote DOM to process a next step. Uses waitFor():
等到一个元素在远程DOM中不存在,然后去执行下一步.使用waitFor():

casper.start('http://foo.bar/');
casper.waitWhileSelector('.selector', function() {
    this.echo('.selector is no more!');
});
casper.run();

waitForSelectorTextChange()

具体样式: waitForSelectorTextChange(String selectors[, Function then, Function onTimeout, Number timeout])
Waits until the text on an element matching the provided selector expression is changed to a different value before processing the next step. Uses
等到一个元素的文本匹配给定的选择器表达式被改变为不同的值,然后执行下一步.

waitFor():

casper.start('http://foo.bar/');
casper.waitForSelectorTextChange('.selector', function() {
    this.echo('The text on .selector has been changed.');
});
casper.run();

waitForText()

具体样式: waitForText(String text[, Function then, Function onTimeout, Number timeout])
New in version 1.0.
Waits until the passed text is present in the page contents before processing the immediate next step. Uses waitFor():
等到被传入的文本在页面的内容中出现.然后执行下一步.

casper.start('http://why.univer.se/').waitForText("42", function() {
    this.echo('Found the answer.');
});
casper.run();

waitUntilVisible()

具体样式: waitUntilVisible(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression is visible in the remote DOM to process a next step. Uses waitFor().
等到一个元素和在远程DOM和给定的选择器表达式可见,然后执行下一步

waitWhileVisible()

具体样式: waitWhileVisible(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression is no longer visible in remote DOM to process a next step. Uses waitFor():
等到一个元素和在远程和给定的选择器表达式不在可见,然后执行下一步.

var casper = require('casper').create();
casper.start('https://www.example.com/').thenClick('html body div p a', function () {
    this.waitWhileVisible('body > div:nth-child(1) > p:nth-child(2)', function () {
        this.echo("The selected element existed in previous page but doesn't exist in this page.");
    })
}).run();

warn()

具体样式: warn(String message)
Logs and prints a warning message to the standard output:
记录并且打印一个警告信息到标准输出.

casper.warn("I'm a warning message.");

Note
Calling warn() will trigger the warn event.
*
*
调用warn方法将会触发warn事件.
*

withFrame()

具体样式: withFrame(String|Number frameInfo, Function then)
New in version 1.0.
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:
页面上先问的选择仅仅存在到步骤被执行完:

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

withPopup()

具体样式: withPopup(Mixed popupInfo, Function then)

New in version 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:
页面上先问的选择仅仅存在到步骤被执行完:

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

Note
The currently loaded popups are available in the Casper.popups array-like property.
*
*
笔记
当前载入的弹窗在caseper种可选的.弹窗像数组属性.
*

zoom()

具体样式: zoom(Number factor)
New in version 1.0.
Sets the current page zoom factor:
这只当前页面的缩放系数:

var casper = require('casper').create();
casper.start().zoom(2).thenOpen('http://google.com', function() {
    this.capture('big-google.png');
});
casper.run();
posted @ 2019-09-12 17:42  luyuqiang  阅读(168)  评论(0编辑  收藏  举报