Javascript-Nightmare.JS无限滚动操作

Javascript - Nightmare.JS infinite scroll action

本文关键字:操作 滚动 无限 JS Javascript-Nightmare      更新时间:2023-09-26

我做错了什么?我想向下滚动一页,直到选择器消失。

    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的原始答案。)

这是一个非常天真的方法来回答您的问题:

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()调用,以可能减少延迟并提高鲁棒性。不过,这应该足以让你开始。


编辑:您询问了选择器的问题,您可以将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查询,这不一定能保证。