Javascript-Nightmare.JS无限滚动动作 [英] Javascript - Nightmare.JS infinite scroll action
问题描述
我在这里做错了什么?我想向下滚动页面,直到选择器消失.
What am I doing wrong here? I want to scroll-down a page until the selector is gone.
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()
推荐答案
(从移植我的原始答案)噩梦#625 .)
这是一种非常的幼稚方法,可以回答您的问题:
This is a very naive method to answer your question:
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');
});
这种方法存在问题:当您访问的页面实际上实际上是无限滚动,以上内容将永无止境.同样,可以用等待滚动元素计数更改来替换.wait()
调用,以可能减少等待时间并提高鲁棒性.尽管如此,这应该足以让您入门.
This approach has problems: when you're going against a page that actually is an infinite scroll, the above will never end. Also, the .wait()
call could be replaced with waiting for the scroll element count to change to possibly reduce latency and increase robustness. Still, this should be enough to get you started.
您询问一个选择器,您可以交换while
子句以使用一个选择器,而不用看增加的高度.从臀部看,像这样:
You asked about a selector, you could swap the while
clause to use a selector instead of looking at increasing height. From the hip, something like:
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
查询,但不一定可以保证.
This approach still has problems: for one, you're relying on the page to satisfy the while
query, which isn't necessarily guaranteed.
这篇关于Javascript-Nightmare.JS无限滚动动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!