在CasperJS's求值中向函数传递参数

Passing parameters to function in CasperJS's evaluate

本文关键字:函数 参数 CasperJS      更新时间:2023-09-26

如何将参数传递给CasperJS中的函数?

    //Should be logged in at this point
    casper.then(function() {
        var counter = 0;
        var cap = 500;
        this.evaluate(function(counter) {
            var children = $('.companies-using-service').children();
            while (counter < children.length) {
                child = children[counter];
                console.log($(child).find('a').attr('data-hint'));
                counter++;
            }
        }, counter);
    });
};
var scrapeClients = function(counter) {
    var children = $('.companies-using-service').children();
    while (counter < children.length) {
        child = children[counter];
        console.log($(child).find('a').attr('data-hint'));
        counter++;
    }
}

上面,我可以使用未命名函数传递参数。但是,我希望将函数scrapeClients传递给评估函数。在这种情况下,我尝试了以下this.evaluate(scrapeClients(counter), counter)。然而,这不起作用,错误说它找不到$变量。

函数是JavaScript中的一等公民。你可以像对待变量一样对待它们。你可以传阅。这意味着您不希望

this.evaluate(scrapeClients(counter), counter)

而是
this.evaluate(scrapeClients, counter)

在第一种情况下,实际上是直接调用函数。由于该函数使用了一些仅在casper.evaluate内部可用的页面属性,因此这将抛出错误并停止脚本。