CasperJS中的条件语句

anh*_*dbk 6 javascript phantomjs casperjs

我刚刚将CasperJS用于我的项目.它的语法清晰易学.但是通过它的文档,我从来没有发现有关条件语句的任何内容.例如,如果我们可以按以下方式使用CasperJS,那么它可能很有用:

var casper = require('casper').create();
var no_error = false;

casper.start('http://casperjs.org/', function() {
    this.echo(this.getTitle());
    no_error = true;
});

if (no_error) {
    casper.thenOpen('http://phantomjs.org', function() {
        this.echo(this.getTitle());
    });
}

casper.run();
Run Code Online (Sandbox Code Playgroud)

有没有办法自定义CasperJS这样的工作?

Art*_* B. 7

是的,否则这样的同步功能casper.exists是没有意义的.

在您的示例中no_error永远不会true,因为casper.start回调是在if (no_error)长时间评估时异步执行的.

你必须嵌套一些步骤(所有wait*then*功能都是步骤)来做到这一点:

var casper = require('casper').create();
var no_error = false;

casper.start('http://casperjs.org/', function() {
    this.echo(this.getTitle());
    no_error = true;
});

casper.then(function(){
    if (no_error) {
        casper.thenOpen('http://phantomjs.org', function() {
            this.echo(this.getTitle());
        });
    }
});

casper.run();
Run Code Online (Sandbox Code Playgroud)

您可以嵌套步骤函数,但是您必须记住,在步骤之后不应该使用同步函数,因为它将以相反的方式执行.

casper.then(function(){
    casper.thenOpen('http://phantomjs.org', function() {
        this.echo("1: " + this.getTitle());
    });
    this.echo("2: " + this.getTitle());
});
Run Code Online (Sandbox Code Playgroud)

将先打印2然后打印1.

同步

如果同步返回条件数据,则可以直接对其进行评估

casper.start('http://casperjs.org/', function() {
    var array = this.evaluate(function(){....});
    if (array && array.length > 2) {
        this.thenOpen(...);
    }
});
Run Code Online (Sandbox Code Playgroud)

根本不需要额外的步骤.

异步

这是它变得有趣的地方.例如,如果您必须在页面上下文中触发长时间运行的脚本(它不限于页面上下文),则必须等待其在casper上下文中完成.您将需要一个指标变量.

casper.thenEvaluate(function(){
    longRunningFunction(function callback(){
        window.__someIndicator = true;
    });
});

casper.waitFor(function check(){
    return this.evaluate(function(){
        return !!window.__someIndicator;
    });
}, function then(){
    this.thenOpen(...);
}, function onTimeout(){
    this.echo("failed");
    this.thenOpen(...); // open something else
});
Run Code Online (Sandbox Code Playgroud)

有时你没有可能的回调.在这种情况下,DOM可能会发生变化,您必须等待这些更改.

结论

第一个代码段中的示例并不真正有用,应该与其他方法之一进行交换.