for 循环在 CasperJS 中是否工作以等待某些东西?

Do for loops work in CasperJS for waiting for something?

我希望我的程序检查是否每 500 毫秒加载了一些东西,直到它找到它。 waitForSelector 不起作用(不要问;它只是不起作用)。但是,casper.exists("css3path") 确实找到了它。

这是我的代码,我不知道我是否只是在我没有看到的真正基本层面上犯了一些愚蠢的错误,或者 for 循环是否不起作用,或者问题是什么。

casper.then(function(){
    for(int i = 0; i < 100; i++){
        if(casper.exists('#bookmark-FSE')){
            i = 100;
        } else{
            casper.wait(500)
            this.echo(i + 'seconds')
        };
    };
});
casper.then(function(){
    //rest of my code

我知道错误在这里,因为如果我用一个愚蠢的 wait(time, function(){ 替换整个东西,它就可以工作。问题是它花费的时间变化很大(3->6 秒) 并且我想缩短它。当我尝试 运行 它时,我收到一条语法错误消息。仅供参考,我使用的是 phantomjs 1.9.2 版。我做错了什么,是吗还有其他方法吗(没有 waitFors 在工作)?

您不能使用任何循环来等待 JavaScript 中的内容。由于 JavaScript 没有阻塞 sleep() 功能或类似的功能,因此无法检查某些条件并在循环中等待。

所有then*wait*函数都是CasperJS中的异步步函数。也就是说通过调用then,匹配步骤只在CasperJS的异步环境中被调度。

您可以像这样使用 CasperJS 轻松地重新创建 waitFor()

casper.myWaitFor = function(test, then, onTimeout, timeout){
    timeout = timeout || this.options.waitTimeout; // 5000
    return this.then(function(){
        if (test.call(this)) {
            if (then) {
                then.call(this);
            }
        }
        this.wait(500, function _then(){
            if (timeout - 500 > 0) {
                this.myWaitFor(test, then, onTimeout, timeout - 500);
            } else if (onTimeout) {
                onTimeout.call(this);
            } else {
                throw new CasperError("Waited without success");
            }
        });
    });
};

casper.myWaitForSelector = function(selector, then, onTimeout, timeout){
    return this.myWaitFor(function(){
        return this.exists(selector);
    }, then, onTimeout, timeout)
};

这样使用:

casper.start(url)
    .then(function(){ /* do something */})
    .myWaitForSelector('#bookmark-FSE', function(){
        this.echo("success");
    })
    .run();

我怀疑这对你有帮助,但它是 waitFor() 的另一个实现。


您收到语法错误,因为 JavaScript 中没有 int。你的意思可能是 var.