我正在尝试使用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')
答案 0 :(得分:1)
元素不是空的,只是不会在控制台日志中显示结果。
您必须访问它们上的数据(例如,textContent
)
尝试一下:
Array.prototype.slice.call(dom.window.document.getElementsByTagName("p")).map(p => {
console.log(p.textContent);
}