querySelectorAll()在与jsdom一起使用时返回空节点列表

时间:2017-04-26 13:00:49

标签: node.js jsdom selectors-api

我正在尝试使用Node.js我的jsdom应用从维基百科页面抓取一些信息。以下是我正在做的事情的一个例子:

jsdom.env({
    url: "https://en.wikipedia.org/wiki/Bill_Gates",
    features: {
        FetchExternalResources: ['script'],
        ProcessExternalResources: ['script'],
        SkipExternalResources: false,
    },
    done: function (err, window) {
        if (err) {
            console.log("Error: ", err)
            return;
        }

        var paras = window.document.querySelectorAll('p');
        console.log("Paras: ", paras)
    }
});

奇怪的是querySelectorAll('p')返回NodeList个空元素:

Paras:  NodeList {
  '0': HTMLParagraphElement {},
  '1': HTMLParagraphElement {},
  '2': HTMLParagraphElement {},
  '3': HTMLParagraphElement {},
  '4': HTMLParagraphElement {},
  '5': HTMLParagraphElement {},
  '6': HTMLParagraphElement {},
  '7': HTMLParagraphElement {},
  ...
  62': HTMLParagraphElement {} }

关于可能出现什么问题的任何想法?谢谢!

修改

window.document.querySelectorAll('p')替换为window.document.getElementsByTagName('p')

时,我得到的结果相同

1 个答案:

答案 0 :(得分:1)

元素不是空的,只是不会在控制台日志中显示结果。 您必须访问它们上的数据(例如,textContent

尝试一下:

Array.prototype.slice.call(dom.window.document.getElementsByTagName("p")).map(p => {
    console.log(p.textContent);
}