Javascript - Nightmare.JS 无限滚动 Action

标签 javascript infinite-scroll nightmare

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

    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/

相关文章:

javascript - 使用nightmare.js发出各种请求

javascript - 逻辑回归不具有泛化能力

javascript - 打开后将浏览器滚动条与模态窗口绑定(bind)

android - 如何使用 Volley 请求在 android 中执行无限滚动

java - 列表页面 RecyclerView 无限滚动在放入 NestedScrollView 时不起作用

javascript - 与开发工具交互,同时使用 .evaluate 抓取 dreamer.js

nightmare - Nightmare.js和IE兼容模式

javascript post 不执行功能但加载 url

javascript - 在生产中使用 node.js?

html - ion-infinite-scroll 极少发射