【发布时间】:2018-02-20 08:29:44
【问题描述】:
我正在运行一个 Nightmare.js 脚本,并在其中尝试require lodash
(使用 npm 安装在本地,在 node_modules 中,在 package.json 中注册)。
index.js:
var Nightmare = require('nightmare');
var _ = require('lodash');
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function getElms(elm) {
var elsm = document.querySelectorAll(elm);
return _.map(elsm, function(elem){ return elem.innerHTML; });
}
var someWebsite = new Nightmare({ show: false })
.goto( ***some url*** )
.wait(getRandomInt(2500, 5000))
.evaluate(function () {
var elsm = document.querySelectorAll(***some selector***);
return _.map(elsm, function(elem){ return elem.innerHTML; });
// return getElms(***some selector***);
}).then(function(linkstexts) {
console.log(linkstexts)
});
-
但我明白了:
UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):_ 未定义
- 如果我取消注释并使用
return getElms(***some selector***);,则会出现类似问题
- 如果我取消注释并使用
这是 package.json
{
"name": "nightxp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"lodash": "^4.17.4",
"nightmare": "^2.10.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
我错过了什么?
更新
我尝试将 lodash 传递给浏览器范围,并以 catch() 完成,
但不知何故,lodash 变量仍然没有被传递到作用域(以hackernews 为例):
var Nightmare = require('nightmare');
var lodash = require('lodash');
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var facebook = new Nightmare({ show: false })
.goto('https://news.ycombinator.com')
.wait(getRandomInt(5500, 6000))
.evaluate( (lodash) => {
var elsm = document.querySelectorAll('tr td.title a.storylink');
return lodash.map(elsm, function(elem){ return elem.innerHTML; });
}, lodash).then(function(titles) {
console.log(titles)
}).catch(function (error) {
console.error('Error:', error);
});
这就是我得到的:
C:\Projects\nightmare>set DEBUG=nightmare & node index.js
nightmare queuing process start +0ms
nightmare queueing action "goto" for https://news.ycombinator.com +4ms
nightmare queueing action "wait" +2ms
nightmare queueing action "evaluate" +0ms
nightmare running +1ms
Error: Cannot read property 'map' of undefined
【问题讨论】:
-
可能是因为你调用
.then(...)后没有.catch(...) -
未处理的承诺拒绝是因为您没有捕获。但真正的问题是为什么
_首先是未定义的。你确定你运行了npm install并且它实际上在 node_modules 中? -
@spencer.sm 事情是,当我没有遍历数组并且只提取一个元素时,没关系。即使没有 .catch()
-
@Mark_M 是的,lodash 在 node_modules 中。我跑了
npm install lodash --save
标签: node.js npm node-modules package.json nightmare