我在javascript中使用Nightmare创建网络抓取工具,但是评估功能未返回正确的信息。似乎它能够返回原始类型(int,字符串等),但不能返回“querySelectorAll”中的元素列表。以下代码可以正常工作:
var Nightmare = require('nightmare'); // make a new nightmare
var nightmare = Nightmare({ show: true }); // display it (change to false for text only)
nightmare
.goto('http://stackoverflow.com/questions') // go to stack overflow
.evaluate(function () {
var all_options = document.querySelectorAll(".summarycount");
return all_options[0].innerHTML;
})
// .end()
.then(function (result) {
console.log(result);
})
.catch(function (error) {
console.error('Search failed:', error);
});
并打印出“13,844,183”或当前所问问题的数量。但是,当我尝试从评估函数返回所有选项时,请更改评估,然后像下面这样执行函数:
.evaluate(function () {
var all_options = document.querySelectorAll(".summarycount");
return all_options;
})
// .end()
.then(function (result) {
console.log(result[0].innerHTML);
})
它只是打印未定义。因此,评价函数返回的值不是所有匹配的DOM元素的正确列表。有没有办法解决?理想情况下,脚本将能够从列表中找到多个元素,选择每个元素,然后在页面上运行更多代码(可能涉及选择更多选项),然后评估结果。
最佳答案
问题是评估必须返回原始类型。我仅通过处理评估函数中所有数据的单击和处理就解决了部分问题。
关于javascript - Nightmare 没有从评估中返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918314/