1

我正在尝试从 Stackoverflow 主页获取问题标题。下面是我的 nightmareJS 代码。

var Nightmare = require('nightmare');
var startingLink = "http://stackoverflow.com"

var nightmare = Nightmare({show:true});

nightmare 
    .goto(startingLink)
    .evaluate(function() {
        return document.getElementsByClassName('question-hyperlink')
    })
    .end()
    .then(function(content) {
        console.log(content);
    })

当我在 Chrome 控制台中运行时,它可以工作。

结果 Chrome 控制台

然而,在 nightmareJS 中,这是我的输出。

ming_o01 (master) nightmare1 $ DEBUG=nightmare node stackoverflow.js
  '48': {},
  '49': {},
  '50': {},
  '51': {},
  '52': {},
  '53': {},
  '54': {},
  '55': {},
  '56': {},
  '57': {},
  '58': {},
  '59': {},
  '60': {},
  '61': {},
  '62': {},
  '63': {},
  '64': {},
  '65': {},
  '66': {},
  '67': {},
  '68': {},
  '69': {},
  '70': {},
  '71': {},
  '72': {},
  '73': {},
  '74': {},
  '75': {},
  '76': {},
  '77': {},
  '78': {},
  '79': {},
  '80': {},
  '81': {},
  '82': {},
  '83': {},
  '84': {},
  '85': {},
  '86': {},
  '87': {},
  '88': {},
  '89': {},
  '90': {},
  '91': {},
  '92': {},
  '93': {},
  '94': {},
  '95': {} }
ming_o01 (master) nightmare1 $

感谢关于为什么我的对象是空的建议。请参阅图像以获取 HTML 和 Chrome 控制台的屏幕截图以及结果。

4

1 回答 1

2

(注意:此对话是来自segmentio/nightmare#617的端口。)

我怀疑 DOMElement 的部分是不可枚举的,因此不会跨越 IPC 边界。换句话说,它不会很好地序列化。

修复它相当简单:在.evaluate(). 假设您想要问题标题和链接:

var Nightmare = require('nightmare');
var startingLink = "http://stackoverflow.com"

var nightmare = Nightmare({
  show: true
});

nightmare
  .goto(startingLink)
  .evaluate(function() {
    var elements = Array.from(document.getElementsByClassName('question-hyperlink'));
    return elements.map(function(element) {
      return {
        href: element.href,
        title: element.innerText
      }
    });
  })
  .end()
  .then(function(content) {
    console.log(content);
  })

请注意,使用Array.from是故意的:document.getElementsByClassName()返回一个类似数组的对象,称为HTMLCollection.

于 2016-05-20T20:23:06.693 回答