如何使casperj重复循环直到满足特定条件?[英] How can I make casperjs repeat a loop until a certain condition is met?

问题描述

我试图让Casperjs处理以下情况:

网页加载,然后在该页面中,它加载数据项 以及一个"阅读更多"按钮,从而加载了更多数据 项目.

我需要脚本来递归检查"更多读取"按钮是否存在(由于有很多数据项要加载) jpeg.

我已经尝试编写下面的代码,但是它并没有像我希望的那样循环.它只需单击一次按钮,然后输出图像,即使更多的数据加载,该按钮仍然存在以再次单击.

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();

推荐答案

庇护有正确的想法,我修改了我的代码,解决方案在下面.

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://www.itbaoku.cn/post/1740005.html