不能 运行 FOR 内部循环.evaluate (node-horseman / phantomjs)

cant run FOR loops inside .evaluate (node-horseman / phantomjs)

大家好!

我正在尝试用 node-horseman 做一个网络爬虫,这样可以更容易地使用 phantomJS。但是我卡在了一点。

显然,我不能在 .evaluate 中 运行 for 循环,对吗?

我的代码要点:

https://gist.github.com/matheus-rossi/bc4c688264be072ded4ff7ee3f933bc2.js

如您所见,如果我 运行 在浏览器中使用完全相同的代码,则一切正常,如下图所示:

Code running OK in the browser

但是如果我 运行 node-horseman 中的代码,我得到这个:

Unhandled rejection eval@[native code]
evaluate

global code
evaluateJavaScript@[native code]
evaluate@phantomjs://platform/webpage.js:390:39
phantomjs://code/bridge.js:121:61    at Horseman.<anonymous> 
(/home/matheus/Documentos/NodeJs/node-horseman/node_modules/node-
horseman/lib/actions.js:839:38)
at Horseman.tryCatcher (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromiseCtx (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/promise.js:606:10)
at Async._drainQueue (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/async.js:138:12)
at Async._drainQueues (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/home/matheus/Documentos/NodeJs/node-horseman/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:781:20)
at tryOnImmediate (timers.js:743:5)
at processImmediate [as _immediateCallback] (timers.js:714:5)

这是我在 index.js 中的代码,运行s node-horseman

var Horseman = require('node-horseman')
var horseman = new Horseman()

horseman
.open('http://www.angeloni.com.br/super/index')
.status()
.evaluate(function(){

const descNode = document.querySelectorAll('.descr a')
const desc = Array.prototype.map.call(descNode, function (t) { return t.textContent })

const valueNode = document.querySelectorAll('.price a')
const value = Array.prototype.map.call(valueNode, function (t) { return t.textContent })

const finalData = []

for (let i=0 ; i < desc.length; i ++) {
  let item = {}
  item['desc'] = desc[i]
  item['value'] = value[i]
  finalData.push(item)
}

return finalData

})
.then(function(finalData){
  console.log(finalData)
})
.close()

我错过了什么?

编辑 - 在 promise 中包含 .catch 后,得到了这个新信息:

  message: 'Expected an identifier but found \'item\' instead',

您缺少的是 phantom.js 运行ning javascript 在与节点不同的环境中。与许多浏览器一样,并非所有优秀的 es6 语言特性都在此环境中可用(目前)。

如果我 运行 你的代码,我使用 let 从 phantom.js 得到错误。将它们更改为 var 使您的代码对我有用。

此外,在 promise 之后添加 .catch() 是个好主意,因为那样你会得到更好的错误,这在这种情况下可能很有用。