我正在尝试将 NightmareJS v2 和 Vo 与 Node.JS 一起使用来浏览一些搜索词并从中收集数据。我的代码如下:
const nightmare = require('nightmare'),
vo = require('vo'),
nbot = nightmare({ title: 'Bot',
show: true });
const searchTerms = ['spacex', 'tesla', 'elon musk', 'hyperloop']; // EXAMPLE SEARCH TERMS
vo(run)(function(err) {
if (err) throw err
});
function * run() {
yield nbot.goto('http://google.com');
yield * forEach(searchTerms, gen);
yield nbot.end()
.then(function(result) {
console.log(result) // STUFF SHOULD BE LOGGED HERE
});
}
function * gen(item) {
yield nbot.wait('input[title="Search"]')
.click('input[title="Search"]')
.type('input[title="Search"]', item)
.click('input[name="btnK"]')
.wait(100)
.screenshot(item + '.png')
.insert('input[title="Search"]', '')
.evaluate(function() {
return 'foobar' // STUFF RETURNED HERE
})
}
function * forEach (arr, fn) { // NEEDED BECAUSE FOREACH DOESN'T WORK IN GENERATORS
let i;
for (i = 0; i < arr.length; i++) {
yield * fn(arr[i]);
}
}
根据 NightmareJS 的文档,如果您在 evaluate
中返回某些内容,那么当您使用 then
时,它会被吐出。当我尝试这个时,我变得不确定。我认为这是发电机的问题,但我对它们很陌生,所以我无法判断。感谢帮助。
最佳答案
示例是close,但看起来您正在将生成器与 Promise 语法混合和匹配。 .evaluate()
方法的行为确实如您所描述的那样,但当您使用 vo
(或 co
)时,.then()
将为您处理和管理,将 .then()
的值返回到 yield
表达式的左侧(如果已定义)。另外,就其值(value)而言,您的生成器不会返回值,因此您将(正确地)得到未定义
。
This更深入地了解迭代器、生成器、promises 和 vo
/co
。您可能还想看看nightmare-examples
关于 vo
的文档.
最后,您的示例被修改为从 gen
返回结果,通过 forEach
直到 run
:
const nightmare = require('nightmare'),
vo = require('vo'),
nbot = nightmare({
title: 'Bot',
show: true
});
const searchTerms = ['spacex', 'tesla', 'elon musk', 'hyperloop']; // EXAMPLE SEARCH TERMS
vo(run)(function(err) {
if (err) throw err
});
function* run() {
yield nbot.goto('http://google.com');
var results = yield * forEach(searchTerms, gen);
console.log(results);
yield nbot.end();
}
function* gen(item) {
var value = yield nbot.wait('input[title="Search"]')
.click('input[title="Search"]')
.type('input[title="Search"]', item)
.click('input[name="btnK"]')
.wait(100)
.screenshot(item + '.png')
.insert('input[title="Search"]', '')
.evaluate(function() {
return 'foobar' // STUFF RETURNED HERE
});
return value;
}
function* forEach(arr, fn) { // NEEDED BECAUSE FOREACH DOESN'T WORK IN GENERATORS
let i;
var results = [];
for (i = 0; i < arr.length; i++) {
results.push(yield * fn(arr[i]));
}
return results;
}
关于javascript - NightmareJS 无法使用 vo 进行评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37537357/