【问题标题】:Web automation, Events and Execution Flow in CasperJSCasperJS 中的 Web 自动化、事件和执行流程
【发布时间】:2014-05-15 21:28:45
【问题描述】:

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

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

  1. 加载页面

  2. 存储页面的图像

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

  4. 等待函数返回结果

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

  6. 提交表格

这是一个代码 sn-p,它试图解释我想出的解决方案:

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 环境之间传递。

【问题讨论】:

  • emit 不是这样运作的。 emit 触发回调您应该以同步方式执行 longProcess。你用casper.wait(20000)半同步试过了吗?
  • 我想要实现的实际上非常简单:1)开始网络自动化 2)暂停自动化并调用传递参数的外部函数 3)从函数中检索结果 4)使用结果恢复表单填充。我应该把casper.wait放在哪里?如果外部进程耗时超过 20000ms 怎么办?

标签: javascript casperjs webautomation


【解决方案1】:

也许是这样的:

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

【讨论】:

  • 显然this.emit('image.processed') 将始终返回undefined,即使我在return 语句之前强制processedValue = 'some_value';。这是将值返回到emit 的正确方法吗?
  • 如何在我的自定义事件中分配一个全局变量?我尝试使用window.processedValue = processedValue,但它会引发错误:ReferenceError: window is not defined
  • 我用新的 sn-p 编辑了原始问题。尝试访问 globProcessValue 时会抛出 ReferenceErrorimage.processed的初衷是处理一个PNG后返回一个字符串值,最多需要15-20秒。
  • 我之前的cmets错了,刷新帖子:p
  • 嘿@Fanch 在stackoverflow之外有什么方法可以联系到你吗?我有一个小脚本,希望得到您的建议。提前致谢
猜你喜欢
  • 2019-06-17
  • 2018-09-12
  • 1970-01-01
  • 2017-09-10
  • 2010-12-31
  • 2019-12-08
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多