我在这里做错了什么?我想向下滚动页面直到选择器消失。
Nightmare.action('scrollPage', function (done) {
this.evaluate_now(function () {
var hitRockBottom = false;
while (!hitRockBottom) {
// console.log("1");
// Scroll the page (not sure if this is the best way to do so...)
this.scrollTo(100000, 0);
// Check if we've hit the bottom
hitRockBottom = this.evaluate(function() {
// console.log("0");
return this.exists('selector') === null;
}); }
}, done)
})
我正在使用:
.goto("link")
.scrollPage()
最佳答案
(从 Nightmare #625 移植我的原始答案。)
这是回答您的问题的非常天真的方法:
var Nightmare = require('nightmare');
var vo = require('vo');
var nightmare = Nightmare({
show: true
});
var run = function * () {
yield nightmare.goto('http://someInfiniteScrollPage.tld');
var previousHeight, currentHeight=0;
while(previousHeight !== currentHeight) {
previousHeight = currentHeight;
var currentHeight = yield nightmare.evaluate(function() {
return document.body.scrollHeight;
});
yield nightmare.scrollTo(currentHeight, 0)
.wait(3000);
}
yield nightmare.end();
};
vo(run)(function(err) {
console.dir(err);
console.log('done');
});
这种方法存在问题:当您访问一个 actually is an infinite scroll 的页面时,以上永远不会结束。此外,.wait()
调用可以替换为等待滚动元素计数更改,以可能减少延迟并提高稳健性。不过,这应该足以让您入门。
编辑:您询问了选择器,您可以交换 while
子句以使用选择器而不是查看增加的高度。从臀部开始,像这样:
var Nightmare = require('nightmare');
var vo = require('vo');
var nightmare = Nightmare({
show: true
});
var run = function * () {
yield nightmare.goto('http://someInfiniteScrollPage.tld');
while(document.querySelectorAll('.someClass').length > 0) {
var currentHeight = yield nightmare.evaluate(function() {
return document.body.scrollHeight;
});
yield nightmare.scrollTo(currentHeight, 0)
.wait(3000);
}
yield nightmare.end();
};
vo(run)(function(err) {
console.dir(err);
console.log('done');
});
这种方法仍然存在问题:首先,您依赖页面来满足 while
查询,这不一定能得到保证。
关于Javascript - Nightmare.JS 无限滚动 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37090854/