问题
I want to repeat steps with CasperJS depending on a variable value coming from the page where I run CasperJS.
To get this value, I do something like:
casper.waitForSelector(".xxxx", function () {
myvalue = this.evaluate(function() {
value = Math.ceil(document.querySelector('#yyy').getAttribute('data-all')/10)-1;
return value;
});
});
Then I try to do something like:
casper.repeat(myvalue, function() {
but it doesn't work because repeat can't find myvalue
variable. Any idea how to achieve something like that?
EDIT
now I try this :
var myvalue = "";
casper.waitForSelector(".xxxx", function () {
myvalue = this.evaluate(function() {
value = Math.ceil(document.querySelector('#connections').getAttribute('data-num-all')/10)-1;
return value;
});
});
casper.repeat(myvalue, function() {
Now I didn't get any synthax error but the repeat isn't executed at all (myvalue=49)
回答1:
I think casper.repeat
and casper.waitForSelector
are executed asynchronously, so repeat()
is executed before the waitFor()
.
Try that :
var myvalue = "";
casper.waitForSelector(".xxxx", function () {
myvalue = this.evaluate(function() {
value = Math.ceil(document.querySelector('#connections').getAttribute('data-num-all')/10)-1;
return value;
});
});
casper.then(function(){
casper.repeat(myvalue, function() {
this.echo("Here the code to be executed 'myvalue' times");
});
});
The then() statement wait for the previous waitForSelector() to be executed before executing repeat().
来源:https://stackoverflow.com/questions/24003667/how-to-have-a-variable-value-for-casper-repeat