我是SpookyJS / CasperJS的新手,我试图找出执行流程。
这就是我想要实现的目标:
加载页面
存储页面图像
将此图像传递给函数并执行它(此过程很长:约15秒)
等待函数返回结果
使用返回的值填充已加载页面
提交表格
这是一个代码片段,试图解释我提出的解决方案:
var globProcessedImage;
try {
var Spooky = require('spooky');
} catch (e) {
var Spooky = require('../lib/spooky');
}
var spooky = new Spooky({
child: {
transport: 'http'
},
casper: {
logLevel: 'debug',
verbose: true
}
}, function (err) {
if (err) {
e = new Error('Failed to initialize SpookyJS');
e.details = err;
throw e;
}
spooky.start('http://example.com/');
spooky.then(function() {
this.captureSelector('./image.png', '#img-node');
});
spooky.waitFor(function() {
this.emit('image.processed');
return globProcessedImage !== undefined;
}, function then() {
processedImage = globProcessedImage;
this.sendKeys('#imagePassword', processedImage);
});
spooky.then(function() {
this.capture('./page.png');
});
spooky.run();
spooky.on('image.processed', function() {
setTimeout(function() {
globProcessedImage = 'my_result_string';
}, 15000);
});
});
spooky.on('error', function (e, stack) {
console.error(e);
if (stack) {
console.log(stack);
}
});
spooky.on('log', function (log) {
if (log.space === 'remote') {
console.log(log.message.replace(/ \- .*/, ''));
}
});
当我运行应用程序时,我收到以下错误:
ReferenceError: Can't find variable: globProcessedImage
如何在SpookyJS中显示globProcessedImage
?这是在Web自动化期间处理外部函数的正确方法吗?
提前致谢。
答案 0 :(得分:0)
编辑:在编写本文时,SpookyJS并不支持按值将对象传递到waitFor
回调的附加语法。所以这段代码不起作用。
与casperjs相比,spookyjs有三种可能的上下文:怪异的上下文,casper上下文和页面上下文。
您尝试访问从casper上下文在spooky上下文中定义的变量。您可以按照本期中所述在上下文之间传递变量:How to make global variables available to functions inside casper?
因此,根据您的代码进行调整,您应该:
var globProcessedImage;
try {
var Spooky = require('spooky');
} catch (e) {
var Spooky = require('../lib/spooky');
}
var spooky = new Spooky({
child: {
transport: 'http'
},
casper: {
logLevel: 'debug',
verbose: true
}
}, function (err) {
if (err) {
e = new Error('Failed to initialize SpookyJS');
e.details = err;
throw e;
}
spooky.start('http://example.com/');
spooky.then(function() {
this.captureSelector('./image.png', '#img-node');
// start longRunning here
});
spooky.waitFor([{spookyGlobProcessedImage: globProcessedImage}, function() {
return spookyGlobProcessedImage !== undefined;
}], [{spookyGlobProcessedImage: globProcessedImage}, function then() {
this.emit('image.processed', spookyGlobProcessedImage);
processedImage = spookyGlobProcessedImage;
this.sendKeys('#imagePassword', processedImage);
}]);
spooky.then(function() {
this.capture('./page.png');
});
spooky.run();
spooky.on('image.processed', function(spookyGlobProcessedImage) {
this.echo("spookyGlobProcessedImage is " + spookyGlobProcessedImage);
});
});
spooky.on('error', function (e, stack) {
console.error(e);
if (stack) {
console.log(stack);
}
});
spooky.on('log', function (log) {
if (log.space === 'remote') {
console.log(log.message.replace(/ \- .*/, ''));
}
});
我不确定spooky.waitFor
是否支持此语法。