CasperJS API介绍

mac2022-06-30  19

 

一、使用标准JavaScript对象作为可选参数构造CasperJS实例

1 直接在create()函数里面使用

var casper = require('casper').create({ clientScripts: [ 'includes/jquery.js', // These two scripts will be injected in remote 'includes/underscore.js' // DOM on every request ], pageSettings: { loadImages: false, // The WebPage instance used by Casper will loadPlugins: false // use these settings }, logLevel: "info", // Only "info" level messages will be logged verbose: true // log messages will be printed out to the console }); 123456789101112

2 在运行时动态添加

var casper = require('casper').create(); casper.options.waitTimeout = 1000; 12

二、最基本API介绍

1. start

原 型: start(String url[, Function then])说 明:配置并启动CasperJS,然后打开url,最后进行then后面的步骤。参数:  url: 需要打开的网址。then: 需要执行的后续操作。

实例:

代码:

var casper = require('casper').create(); casper.start('http://www.baidu.com/', function() { this.echo("Hello Baidu. I am here now."); }); casper.run(); 12345运行结果: 

2. run

原 型:run(fn onComplete[, int time])说 明:执行所有的步骤,当所有的步骤都执行完之后可以执行一个callback。参数:  onComplete: 可选参数,当所有步骤执行完成之后的回调函数。注意:如果使用回调函数,一定要在回调函数里面调用exit(),便于返回。同时,由于调用exit()之后就从回调函数返回,所以在exit()之后的操作不会有任何作用。

实例:

代码:

var casper = require('casper').create(); casper.start('http://www.baidu.com/', function() { this.echo("Hello Baidu. I am here now."); }); casper.run(function() { this.echo('So the whole suite ended.'); this.exit(); // <--- don't forget me! this.echo('After exit().'); //<----Don't be executed. }); 123456789

运行结果: 

3 then

原 型:then(Function then)说 明:通过提供一个简单的函数,使用标准的方式来增加一个导航功能到执行栈。参数:  Function: 简单的函数。

实例:

代码:

var casper = require('casper').create(); casper.start('http://www.baidu.com/'); casper.then(function() { this.echo("I'm in Baidu."); }); casper.then(function() { this.echo('I am a freshman.'); }); casper.then(function() { this.echo('It is amazing. Bye!'); }); casper.run(); 1234567891011121314

运行结果: 

三、综合实例

获取当前访问的HTTP response

代码:

var casper = require('casper').create(); casper.start('http://www.baidu.com/'); casper.then(function() { this.echo("HTTP Response Info:"); this.echo("--------------------------------------"); }); casper.then(function(response) { require('utils').dump(response); }); casper.then(function() { this.echo("--------------------------------------"); this.echo("end"); }); casper.run(); 12345678910111213141516

结果: 

转载:http://blog.csdn.net/Kandy_Ye/article/details/47355169

转载于:https://www.cnblogs.com/c-x-a/p/7267063.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)