How can I make casperjs repeat the loop until a certain condition is met?

I am trying to get casperjs to work with the following situation:

The web page is loaded, then on that page, it loads the ajax data items along with the read more button, which in turn loads some more data items.

I need a script to recursively check if a read more button exists (as there are many data items to load), if so click on it, otherwise continue with the rest of the script and output the full page as jpeg.

I tried to write the code below, but it doesn't work as I hoped. It just clicks the button once, then displays the image even if more data is loaded and the button still exists to be pressed 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();

      

+3


source to share


1 answer


Pius had the right idea, I changed my code, 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();

      

0


source







All Articles