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

问题描述 投票:3回答:1

我正在尝试使用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')时,我得到了相同的结果

node.js jsdom selectors-api
1个回答
1
投票

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

试试这个:

Array.prototype.slice.call(dom.window.document.getElementsByTagName("p")).map(p => {
    console.log(p.textContent);
}
© www.soinside.com 2019 - 2024. All rights reserved.