Javascript CasperJS中的Web自动化、事件和执行流
我是CasperJS的新手,我正在尝试弄清楚执行流程 这就是我想要实现的目标:Javascript CasperJS中的Web自动化、事件和执行流,javascript,casperjs,webautomation,Javascript,Casperjs,Webautomation,我是CasperJS的新手,我正在尝试弄清楚执行流程 这就是我想要实现的目标: 载入一页 存储页面的图像 将此映像传递给函数并执行它(此过程相当长:~15秒) 等待函数返回结果 使用返回的值填充加载页面中表单中的字段 提交表格 这是一段代码片段,试图解释我提出的解决方案: var globProcessedImage; var casper = require('casper').create({ viewportSize: { width: 1024,
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);
});
这将导致引用错误:找不到变量:globProcessedImage
我仍然不清楚web自动化和“外部”功能是如何与CasperJS混合在一起的,以及页面和casper/phantom环境之间的参数是如何传递的。可能类似于:
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
,即使我强制processedValue='some_value'代码>在返回
语句之前。这是将值返回到emit
的正确方法吗?如何在自定义事件中分配全局变量?我尝试了window.processedValue=processedValue
但它抛出了一个错误:ReferenceError:window未定义
我用一个新的片段编辑了原始问题。尝试访问globProcessValue
时抛出ReferenceError
。image.processed
的最初目的是在处理PNG后返回一个字符串值,这需要15-20秒。我以前的评论是错误的,请刷新帖子:pHey@Fanch有没有办法在stackoverflow之外找到你?我有一个小脚本,我想与你的意见。提前感谢这不是emit
的工作方式emit
触发回调。您应该以同步方式执行长流程。您是否使用casper.wait(20000)
半同步地尝试过它?我想要实现的实际上非常简单:1)开始web自动化2)暂停自动化并调用传递参数的外部函数3)从函数检索结果4)使用结果恢复表单填充。我应该把casper.wait
放在哪里?如果外部过程需要超过20000ms怎么办?