1

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

    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()
4

1 回答 1

2

(从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');
});

这种方法存在问题:当您访问实际上是无限滚动的页面时,上述内容将永远不会结束。此外,.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查询,这不一定能保证。

于 2016-05-24T15:30:47.600 回答