我正在尝试使用 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/