0

我是 CasperJS 的新手,我正在尝试弄清楚执行流程。

这就是我想要实现的目标:

  1. 加载页面

  2. 存储页面的图像

  3. 将此图像传递给一个函数并执行它(这个过程很长:~15 秒)

  4. 等待函数返回结果

  5. 使用返回的值在加载的页面中填写表单中的一个字段

  6. 提交表格

这是一个代码片段,试图解释我想出的解决方案:

var globProcessedImage;

var casper = require('casper').create({
    viewportSize: {
        width: 1024,
        height: 768
    }
});

casper.start('http://example.com/');

casper.then(function() {
    this.captureSelector('./image.png', '#img-node');
});

casper.waitFor(function() {
    return globProcessedImage !== undefined;
}, function then() {
    this.sendKeys('#imagePassword', globProcessedImage);
});

casper.then(function() {
    this.capture('./page.png');
});

casper.run();

casper.on('image.processed', function() {
    setTimeout(function() {
        globProcessedImage = 'my_result';
    }, 15000);
});

这导致ReferenceError: Can't find variable: globProcessedImage.

我仍然不清楚 Web 自动化和“外部”功能如何与 CasperJS 混合在一起,以及参数如何在页面和 casper/phantom 环境之间传递。

4

1 回答 1

0

也许是这样的:

var globProcessedImage ;

var casper = require('casper').create({
    viewportSize: {
        width: 1024,
        height: 768
    }
});

casper.start('http://example.com/');

casper.options.waitTimeout = 16000;

casper.then(function() {
    this.captureSelector('./image.png', '#img-node');
    this.emit('image.processed');
});

/*
 * If you need to wait for a fix time, it's okay, but a better way would be to wait in Casper 
 * 'the thing you do with your image' in a waitFor. -> asynchronous. With this solution you combine two timers, this is not the optimized solution.
 */
casper.waitFor(function() {
    return globProcessedImage !== undefined;
}, function then() {
    this.sendKeys('#imagePassword', globProcessedImage);
});

casper.then(function() {
    this.capture('./page.png');
});

casper.run();

casper.on('image.processed', function() {
    setTimeout(function() {
        //when you will emit this event in your script, it will set the value of globProcessedImage to 'my_result' after 15sec
        globProcessedImage = 'my_result';
    }, 15000);
});
于 2014-05-14T15:03:26.323 回答