我希望程序检查是否每500毫秒加载一次,直到找到它为止。 waitForSelector不起作用(不要问;它只是没有)。但是,casper.exists("css3path")
确实找到了它。
这是我的代码,我不知道我是否只是在一个我没有看到的基本级别上犯了一些愚蠢的错误,或者是否为了循环而不是#39工作,或问题是什么。
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
我知道错误在这里,因为如果我用愚蠢的等待替换整个事物(时间,函数(){它的工作原理。问题是它花费的时间变化很大(3-> 6秒)我想缩短它。当我尝试运行它时,我收到语法错误消息。仅供参考,我使用的是phantomjs版本1.9.2。我做错了什么,有没有其他方式(没有waitFors工作)?
答案 0 :(得分:0)
您不能使用任何循环来等待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
。