我想遍历 ul> 中的每个 li> ,然后将它们添加到数组中。我应该如何创建一个 for 循环来返回每个 li 并将它们放入数组中。让 li 进入循环是我卡住的地方。
var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false })
nightmare
.goto('https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux')
.wait(500)
.evaluate(function () {
var ht = document.querySelector('#toc > ul > li.toclevel-1.tocsection-5 > ul
').innerText;
return ht;
})
.end()
.then(function (result) {
console.log(result)
})
.catch(function (error) {
console.error('Search failed:', error);
});
输出:
PS C:\scrapping> node .\2.js
5.1 RHEL 2.1
5.2 RHEL 3
5.3 RHEL 4
5.4 RHEL 5
5.5 RHEL 6
5.6 RHEL 7
PS C:\scrapping>
问题是,当您期望 then() 中的结果时,在 nightmare.ipc 下被调用并尝试将其字符串化/解串以将其发送到您的应用程序。HTMLElements(由 document.querySelectorAll() 返回)可能无法字符串化,并且可以在 browserWindow 的开发人员控制台中看到此类错误
你可以很容易地做到这一点:
const Nightmare = require('nightmare');
const nightmare = Nightmare({
show: true,
openDevTools: true,
});
nightmare
.goto('https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux')
.evaluate(function(selector) {
var links = document.querySelectorAll(selector);
var passed = [];
for(var ii=0; ii<links.length; ii++) {
passed.push(links[ii].textContent);
}
return passed;
}, '#toc > ul > li.toclevel-1.tocsection-5 > ul > li')
.then(function(result) {
console.log(result); // Outputs length.
})
.catch(function(error) {
console.error('Failed', error);
});
//Output
[ '5.1 RHEL 2.1',
'5.2 RHEL 3',
'5.3 RHEL 4',
'5.4 RHEL 5',
'5.5 RHEL 6',
'5.6 RHEL 7' ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句