node.js - querySelectorAll() 与 jsdom 一起使用时返回空 Node 列表

标签 node.js jsdom selectors-api

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

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') 时我得到了相同的结果

最佳答案

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

试试这个:

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

关于node.js - querySelectorAll() 与 jsdom 一起使用时返回空 Node 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634984/

相关文章:

node.js - 如何使用更新插入行为正确更新文档? (Mongo 漏洞 SERVER-10711)

javascript - ES6 将两个变量组合到现有的 javaScript 对象中

javascript - Jest 中从未调用图像 onLoad 处理程序

javascript - document.querySelectorAll 选择特定输入的 id

node.js - 错误 : CAIRO_FORMAT_RGB30 was not declared in this scope

mysql - nodejs 和非阻塞噩梦

javascript - jsdom/cheerio 大大改变了 html

javascript - 使用 Node 和 jsdom 爬虫站点时内存不足

javascript - 为什么JS代码 "var a = document.querySelector(' a[data-a=1 ]');"会报错?

javascript - CSS 选择器从右到左计算。 querySelectorAll() 选择器是否也以这种方式进行评估?