码迷,mamicode.com
首页 > Web开发 > 详细

capserjs-prototype(中)

时间:2019-09-12 18:33:27      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:creat   serve   嵌套   mouseover   rom   ports   伪造   http请求   bad   

evaluateOrDie()

具体样式: evaluateOrDie(Function fn[, String message, int status])
Evaluates an expression within the current page DOM and die() if it returns anything but true:
执行一个表达式在当前页面dom,并且如果没有返回ture,就die掉:

casper.start('http://foo.bar/home', function() {
    this.evaluateOrDie(function() {
        return /logged in/.match(document.title);
    }, 'not authenticated');
});

casper.run();

exit()

具体样式: exit([int status])
Exits PhantomJS with an optional exit status code.
用一个退出状态码退出PhantomJS

Note: You can not rely on the fact that your script will be turned off immediately, because this method works asynchronously. It means that your script may continue to be executed after the call of this method. More info here.
笔记:你不能依赖你脚本会立即退出的事实,因为这个方法是异步执行的.意味着你的脚本在调用这个方法后仍会执行.更多信息

exists()

具体样式: exists(String selector)
Checks if any element within remote DOM matches the provided selector:
检查是否有给定选择皮匹配远程dom:

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

fetchText()

具体样式: fetchText(String selector)
Retrieves text contents matching a given selector expression. If you provide one matching more than one element, their textual contents will be concatenated:
检索一个给的选择器表达式的文本内容.如果你提供了的一个表达式匹配了不止一个元素,他们将会被多行索引

casper.start('http://google.com/search?q=foo', function() {
    this.echo(this.fetchText('h3'));
}).run();

forward()

具体样式: forward()
Moves a step forward in browser’s history:
从浏览器历史中前移一步

casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back();    // http://foo.bar/2
casper.back();    // http://foo.bar/1
casper.forward(); // http://foo.bar/2
casper.run();

Also have a look at back().
看一眼forward方法

log()

具体样式: log(String message[, String level, String space])
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:
在一个可选位置,使用一个可选的等级记录一个信息.可选等级为debug, info, warning and error.空间是你能为你过滤你的日志设置的.默认情况下,casper日志文件在两个独立的空间:phantom和remote.为了去辨别从远程的PhantomJS环境发生了什么:

casper.start('http://www.google.fr/', function() {
    this.log("I'm logging an error", "error");
});
casper.run();

fill()

具体样式: fill(String selector, Object values[, Boolean submit])
Fills the fields of a form with given values and optionally submits it. Fields are referenced by their name attribute.
使用给的值填入字段到一个表格,并且可选是否提交.字段参考他们的name属性.

Changed in version 1.1:
To use CSS3 or XPath selectors instead, check the fillSelectors() and fillXPath() methods.
Example with this sample html form:
使用css3或者Xpath选择器替代,查看fillSelectors()和fillXPath()方法.
用这个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>

A script to fill and submit this form:
脚本将会填入并且提交表格:

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':      'chuck@norris.com',
        '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();
});

The fill() method supports single selects in the same way as text input. For multiple selects, supply an array of values to match against:
fill方法支持单个select的操作.对于复合select,提供一个数组去匹配:

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

A script to select multiple options for category in this form:
表格中复合文本框分类选项:

casper.then(function() {
   this.fill('form#contact-form', {
       'categories': ['0', '1'] 
        // Friends and Family
   });
});
  • Warning
    The fill() method currently can’t fill file fields using XPath selectors; PhantomJS natively only allows the use of CSS3 selectors in its uploadFile() method, hence this limitation.
    Please Don’t use CasperJS nor PhantomJS to send spam, or I’ll be calling the Chuck. More seriously, please just don’t.
  • 警告
    fill方法目前不能使用Xpath选择器填入file的文本.原生PhantomJS只允许在uploadFile方法中使用css选择器,
    所以有这个限制.
    请既不要使用casperjs,也不要使用phantomjs去发送垃圾,否则我们将会给Chuck打电话.更重要的是,别这么做

fillSelectors()

具体样式: fillSelectors(String selector, Object values[, Boolean submit])
New in version 1.1.
Fills form fields with given values and optionally submits it. Fields are referenced by CSS3 selectors:
使用给的值填入字段到一个表格,并且可选是否提交.字段参考他们的name属性.

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"]':      'chuck@norris.com',
        'input[name="cc"]':         true,
        'input[name="attachment"]': '/Users/chuck/roundhousekick.doc'
    }, true);
});

fillLabels()

具体样式: fillLabels(String selector, Object values[, Boolean submit])
New in version 1.1.
Fills a form with provided field values using associated label text Fields are referenced by label content values:
使用给的值填入字段到一个表格使用关联的标签文本框参考标签内容的值

casper.start('http://some.tld/contact.form', function() {
    this.fillLabels('form#contact-form', {
        Email:         'chuck@norris.com',
        Password:      'chuck',
        Content:       'Am watching thou',
        Check:         true,
        No:            true,
        Topic:         'bar',
        Multitopic:    ['bar', 'car'],
        File:          fpath,
        "1":           true,
        "3":           true,
        Strange:       "very"
    }, true);
});

fillXPath()

具体样式: fillXPath(String selector, Object values[, Boolean submit])
New in version 1.1.
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:
用给的值填写到表格并且可选择是否提交.然而表格元元素经常和css3关联:

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"]':      'chuck@norris.com',
        '//input[@name="cc"]':         true,
    }, true);
});
  • Warning
    The fillXPath() method currently can’t fill file fields using XPath selectors; PhantomJS natively only allows the use of CSS3 selectors in its uploadFile() method, hence this limitation.
  • 警告
    fillXPath方法目前不能使用Xpath选择器填入file的文本.原生PhantomJS只允许在uploadFile方法中使用css选择器,所以有这个限制.

getCurrentUrl()

具体样式: getCurrentUrl()
Retrieves current page URL. Note that the url will be url-decoded:
获取当前网页的URL.注意URL将会是url-decoded过的

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

getElementAttribute()
具体样式: getElementAttribute(String selector, String attribute)
New in version 1.0.
Retrieves the value of an attribute on the first element matching the provided selector:
获取给定的选择器的第一个元素的属性值

var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google"
});
casper.run();

getElementsAttribute()
具体样式: getElementsAttribute(String selector, String attribute)
New in version 1.1.
Retrieves the values of an attribute on each element matching the provided selector:
获取给的选择器所有的元素的属性值

var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementsAttribute('div[title="Google"]', 'title')); // "['Google']"
});
casper.run();

getElementBounds()
具体样式: getElementBounds(String selector)
Retrieves boundaries for a DOM element matching the provided selector.
获取给定的选择器的dom元素的绑定
It returns an Object with four keys: top, left, width and height, or null if the selector doesn’t exist:
返回一个的4个key的对象:top,left,width,height,否则选择器不存在返回null:

var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
    require('utils').dump(this.getElementBounds('div[title="Google"]'));
});
casper.run();
/*This will output something like:
将会这样输出:
{
    "height": 95,
    "left": 352,
    "top": 16,
    "width": 275
}
*/

getElementsBounds()

具体样式: getElementsBounds(String selector)
New in version 1.0.
Retrieves a list of boundaries for all DOM elements matching the provided selector.
获取所有给定选择器的dom元素的绑定
It returns an array of objects with four keys: top, left, width and height (see getElementBounds()).
返回一个4个key数组对象:top,left,width,height(去看getElementBounds)

getElementInfo()

具体样式: getElementInfo(String selector)
New in version 1.0.
Retrieves information about the first element matching the provided selector:
获取第一个给定的选择器匹配的元素的信息:

casper.start('http://google.fr/', function() {
    require('utils').dump(this.getElementInfo('#hplogo'));
});

//Gives something like:
//如下显示:
{
    "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&amp;&amp;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
}
  • Note
    This method does not return a DOM element, only a simple object representation of it; this is because the casper environment has no direct access to the scraped page one.
  • 笔记
    这个方法不再返回dom元素,仅仅返回它的一个对象.因为casper环境不能直接获取擦掉的页面

getElementsInfo()

具体样式: getElementsInfo(String selector)
New in version 1.1.
Retrieves information about all elements matching the provided selector:
获取给定的选择器的所有元素的信息:

casper.start('http://google.fr/', function() {
    require('utils').dump(this.getElementsInfo('#hplogo'));
});

//Gives something like:
//如下显示:
[
    {
        "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&amp;&amp;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
    }
]
  • Note
    This method does not return a NodeList, only a simple array of object representations of matching elements; this is because the casper environment has no direct access to the scraped page one.
  • 笔记
    这个方法不再返回node列表,仅仅返回它的一个数组对象.因为casper环境不能直接获取擦掉的页面

getFormValues()

具体样式: getFormValues(String selector)
New in version 1.0.
Retrieves a given form all of its field values:
获取表格所有的字段的值:

casper.start('http://www.google.fr/', function() {
    this.fill('form', {q: 'plop'}, false);
    this.echo(this.getFormValues('form').q); // 'plop'
});
casper.run();

getGlobal()

具体样式: getGlobal(String name)
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:
使用远程dom环境自己的名获取一个全局的变量.根本上说,getGlobal(‘foo‘) 将会获取页面上的window.foo的值

casper.start('http://www.google.fr/', function() {
    this.echo(this.getGlobal('innerWidth')); // 1024
});
casper.run();

getHTML()

具体样式: getHTML([String selector, Boolean outer])
New in version 1.0.
Retrieves HTML code from the current page. By default, it outputs the whole page HTML contents:
获取当前页面的html代码.从根本上说,将会输出整个html内容:

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

The getHTML() method can also dump HTML contents matching a given selector; for example with this HTML code:
getHTML方法也能够打印给定选择器的html内容.比如以下的html代码:

<html>
    <body>
        <h1 id="foobar">Plop</h1>
    </body>
</html>

You can fetch those contents using:
你能够匹配这个内容使用:

casper.start('http://www.site.tld/', function() {
    this.echo(this.getHTML('h1#foobar')); // => 'Plop'
});

The outer argument allows to retrieve the outer HTML contents of the matching element:
外部变量语序获取外部匹配元素的html文本

casper.start('http://www.site.tld/', function() {
    this.echo(this.getHTML('h1#foobar', true)); // => '<h1 id="foobar">Plop</h1>'
});

getPageContent()

具体样式: getPageContent()
New in version 1.0.
Retrieves current page contents, dealing with exotic other content types than HTML:
获取当前页的内容,使用外来的其他内容类型而不是HTML:

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

getTitle()
具体样式: getTitle()
Retrieves current page title:
获取当前页的title:

casper.start('http://www.google.fr/', function() {
    this.echo(this.getTitle()); // "Google"
});
casper.run();

mouseEvent()

具体样式: mouseEvent(String type, String selector, [Number|String X, Number|String Y])
New in version 0.6.9.
Triggers a mouse event on the first element found matching the provided selector.
在第一个给定选择器匹配的元素上触发鼠标事件.
Supported events are mouseup, mousedown, click, dblclick, mousemove, mouseover, mouseout and for phantomjs >= 1.9.8 mouseenter, mouseleave and contextmenu:
支持的事件有:mouseup,mousedown,click,dbclick,mousemove,mouseover,mouseout和如果phantomjs版本大于1.9.8的mouseenter,mouseleave和contextmenu:

  • warning
    The list of supported events depends on the version of the engine in use. Older engines only provide partial support. For best support use recent builds of PhantomJS or SlimerJS.”
  • 警告
    支持事件依赖于正在使用引擎的版本,老的引擎仅仅支持一部分.因此最好使用最新的phantomJS或者SlimerJS版本.
casper.start(‘http://www.google.fr/‘, function() {
this.mouseEvent(‘click’, ‘h2 a’, “20%”, “50%”);
});
casper.run();

newPage()

具体样式: newPage()
New in version 1.1.
Only available since version 1.1.0.
仅仅1.1.0以上版本可用.
Creates a new WebPage instance:
创建一个网页实例:

casper.start('http://google.com', function() {
    // ...
});
casper.then(function() {
    casper.page = casper.newPage();
    casper.open('http://yahoo.com').then( function() {
        // ....
    });
});
casper.run();

open()

具体样式: open(String location, Object Settings)

Performs an HTTP request for opening a given location. You can forge GET, POST, PUT, DELETE and HEAD requests.
演示为一个给定的地址的http请求.你能够伪造get,post,put,delete和head请求.

Example for a standard GET request:
get请求的基础例子:

casper.start();
casper.open('http://www.google.com/').then(function() {
    this.echo('GOT it.');
});
casper.run();

Example for a POST request:
post请求的基础例子:

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

New in version 1.0.
To POST some data with utf-8 encoding:
post一些utf-8数组的数据

casper.open('http://some.testserver.com/post.php', {
       method: 'post',
       headers: {
           'Content-Type': 'application/json; charset=utf-8'
       },
       encoding: 'utf8', // not enforced by default
       data: {
            'table_flip': '(╯°□°)╯︵ ┻━┻ ',
       }
});

New in version 1.1.
You can also set custom request headers to send when performing an outgoing request, passing the headers option:
你也能传入一个自定义请求的header去发送去当延时一个请求时,传入header选择:

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

reload()

具体样式: reload([Function then])
New in version 1.0.
Reloads current page location:
重载当前连接:

casper.start('http://google.com', function() {
    this.echo("loaded");
    this.reload(function() {
        this.echo("loaded again");
    });
});
casper.run();

repeat()

具体样式: repeat(int times, Function then)
Repeats a navigation step a given number of times:
重复一个给定步骤多少次:

casper.start().repeat(3, function() {
    this.echo("Badger");
});
casper.run();

resourceExists()

具体样式: resourceExists(String|Function|RegExp test)
Checks if a resource has been loaded. You can pass either a function, a string or a RegExp instance to perform the test:
检查一个资源是否被载入.你能够传入一个方法或者一个字符串,或者一个正则实例去验证这个例子:

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();
  • Note
    If you want to wait for a resource to be loaded, use the waitForResource() method.
  • 如果你想要为资源载入等一会,使用waitForResource方法.

run()

具体样式: run(fn onComplete[, int time])
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.
运行整个步骤,在运行完可选执行回调.明显地,调用这些方法命令为的是Casper导航套件.

Casper suite won’t run:
casper套件不会运行:

casper.start('http://foo.bar/home', function() {
    // ...
});
// hey, it's missing .run() here!
//Casper suite will run:
//嘿,缺少run方法这里
//casper将会运行
casper.start('http://foo.bar/home', function() {
    // ...
});
casper.run();

Casper.run() also accepts an onComplete callback, which you can consider as a custom final step to perform when all the other steps have been executed. Just don’t forget to exit() Casper if you define one!:
casper.run方法也接受完成时回调,当所有的其他步骤已经被执行了,考虑自定义结束步骤去验证.

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

Binding a callback to complete.error will trigger when the onComplete callback fails.
绑定一个回调去完成.当完成时的回调出错,错误将会触发.

capserjs-prototype(中)

标签:creat   serve   嵌套   mouseover   rom   ports   伪造   http请求   bad   

原文地址:https://www.cnblogs.com/luyuqiang/p/capserjs-prototype-part2.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!