问题
I'm trying to get casperjs working with the following situation:
A web page loads, then within that page, it ajax loads data items along with a 'read more' button which in turn loads some more data items.
I need the script to recursively check if the 'read more' button exists (as there are many data items to load), if so, click it, else continue with the rest of the script and output the full page as a jpeg.
I've tried by writing the code below, but it doesn't loop as I had hoped. It just clicks the button once, then outputs the image, even though more data loads, and the button still exists for clicking again.
var casper = require('casper').create({
verbose : true,
logLevel : 'debug',
pageSettings : {
"userAgent" : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10',
"loadImages" : false,
"webSecurityEnabled" : false,
"ignoreSslErrors" : true
},
});
var urls = {
login : 'http://www.website.com/login',
details : 'http://www.website.com/details',
};
casper.start(urls.login, function() {
//login stuff
});
//the function I'm trying to recursively loop before moving on to saving the capture image
function checkMore() {
//check to see if the 'read more' button exists
if (casper.exists('a.read-more')) {
//click the button to load more items
casper.click('a.read-more');
//wait for the items to load, then run the check again
casper.wait(3000, function() {
casper.run(checkMore);
});
}
}
casper.thenOpen(urls.details, function() {
//wait for the page along with ajax items to load shortly after
this.wait(3000, function() {
this.run(checkMore);
});
});
casper.then(function() {
//output the result
this.capture('output.jpg');
});
casper.run();
回答1:
Pius had the right idea, I modified my code, the solution is below.
var urls = {
login : 'http://www.website.com/login',
details : 'http://www.website.com/details',
};
casper.start(urls.login, function() {
//login stuff
});
//the function I'm trying to recursively loop before moving on to saving the capture image
function checkMore() {
//check to see if the 'read more' button exists
if (casper.exists('a.read-more')) {
//click the button to load more items
casper.click('a.read-more');
//wait for the items to load, then run the check again
casper.wait(3000, checkMore);
}
}
casper.thenOpen(urls.details, function() {
//wait for the page along with ajax items to load shortly after
this.wait(3000, checkMore);
});
casper.then(function() {
//output the result
this.capture('output.jpg');
});
casper.run();
来源:https://stackoverflow.com/questions/27625935/how-can-i-make-casperjs-repeat-a-loop-until-a-certain-condition-is-met