我正在尝试转到下一页并使用nightmareJS
抓取链接直到最后一个可用页面。虽然我遇到了问题,并且在如何让它工作方面没有任何运气。
法典
const Nightmare = require('nightmare');
const nightmare = Nightmare({ show: true, executionTimeout: 3000})
const imageUrl = [];
function getImages() {
const images = document.querySelectorAll('.item a img');
const img = [];
for(let i = 0; i<images.length; i++) {
img.push(images[i].src);
}
return img;
}
nightmare
.goto('https://hidurl/images/search/dogs/')
.scrollTo(20368, 0)
.wait(1000)
.evaluate(getImages)
.then(a => {
const aFiltered = a.filter(word => word.includes('.jpg'));
for(let i = 0; i<aFiltered.length; i++) {
imageUrl.push(aFiltered[i]);
}
console.log(imageUrl);
return nightmare
.click('#content > div > a')
.scrollTo(20368, 0)
.wait(1000)
.evaluate(getImages)
.then( a => {
const aFiltered = a.filter(word => word.includes('.jpg'));
for(let i = 0; i<aFiltered.length; i++) {
imageUrl.push(aFiltered[i]);
}
console.log(imageUrl);
})
})
.catch(error => {
console.error(error)
})
我想得到一个包含页面上所有可用链接的数组。到目前为止,我最多只能访问两页,而无需重复代码。我正在开始使用 NightMare,并希望在移动时找到一些有关如何浏览多个页面和填充数组的帮助。
好的修复了使用生成器函数和控制流节点库 vo 的问题
const Nightmare = require('nightmare');
const vo = require('vo');
const nightmare = Nightmare({ show: true, executionTimeout: 3000 });
const imageUrl = [];
function getImages() {
const images = document.querySelectorAll('.item a img');
const img = [];
for (let i = 0; i < images.length; i++) {
img.push(images[i].src);
}
return img;
}
vo(run)(function(err, result) {
if (err) throw err;
});
function* run() {
let MAX_PAGE = 5,
currentPage = 0,
nextExists = true;
yield nightmare
.goto('https://someurl/images/search/dogs/')
.scrollTo(20368, 0)
.wait(1000);
nextExists = yield nightmare.exists('#content > div > a');
while (nextExists && currentPage < MAX_PAGE) {
yield nightmare
.scrollTo(20368, 0)
.wait(1000)
.evaluate(getImages)
.then(a => {
const aFiltered = a.filter(word => word.includes('.jpg'));
for (let i = 0; i < aFiltered.length; i++) {
imageUrl.push(aFiltered[i]);
}
});
yield nightmare
.click('#content > div > a')
.wait('body')
.wait(1000);
currentPage++;
nextExists = yield nightmare.exists('#content > div > a');
}
console.table(imageUrl);
yield nightmare.end();
}
现在可以使用 NightMareJS 访问任何带有分页的站点上的许多页面。