CasperJS多次提交和评估,如for循环

时间:2012-12-20 16:52:51

标签: javascript webkit phantomjs casperjs headless-browser

我正在尝试使用CasperJS来自动执行一些通常需要大量时间的步骤。基本上我需要登录我们的CMS并检查是否安装了一些插件。如果它们只是更新它们,但如果它们不是那么就创建它们。我设法登录并进入带有插件列表的页面,但我在这里遇到了麻烦。这是我需要做的,在伪代码中:

for every plugin defined in my config file
    populate the search plugins form and submit it
    evaluate if the response contains my plugin

这是代码

casper.thenOpen(snippetsUrl, function() {
    console.log(colorizer.colorize("###############PROCESSING SNIPPETS###################", 'ERROR'));
    this.capture('snippets.png');

    this.each(Config.snippets.station, function(self, snippet) {
        self.fill('form[id="changelist-search"]', {q: snippet.name}, true);
        self.then(function() {
            this.capture(snippet.name + '.png');
        })
    });
});

我的表单会连续多次提交,然后在“然后”步骤中,我会多次捕获同一页面...如何解决此问题?

1 个答案:

答案 0 :(得分:4)

试试这个:

this.each(Config.snippets.station, function(self, snippet)
{
    self.then(function()
    {
        this.fill('form[id="changelist-search"]', {q: snippet.name}, true);
    });
    self.then(function()
    {
        this.capture(snippet.name + '.png');
    })
});

您的初始代码无效的原因是Capser的then声明了延迟执行步骤。如果未展开,您的代码实际上会执行以下操作:

submit form 1
place capture 1 into a queue
submit form 2
place capture 2 into a queue
submit form 3
place capture 3 into a queue
// then execute the queue
capture 1
capture 2
caprure 3

生成的代码将所有步骤放入队列中,因此它们按正确的顺序执行。