无限滚动刮页

时间:2019-04-13 16:42:17

标签: javascript web-scraping scroll infinite-scroll

我正在尝试将所有产品都放在一个电子商务网站上,该网站使用无限滚动来加载产品,我找到了一种滚动到页面底部的解决方案,但是,似乎没有端点,即使到达页面底部后它仍然继续运行,所以我想知道如何知道页面是否已结束,以便我可以设置条件并停止清除间隔的函数,非常感谢您的帮助。 我正在粘贴当前的解决方案,该解决方案向下滚动到页面末尾,但此后再也不会停止。

(function() {
    var lastScrollHeight = 0, count = 0;
    function autoScroll() {
      count++;
      console.log(count);
      var sh = document.documentElement.scrollHeight;
      if (sh !== lastScrollHeight) {
        console.log(sh, lastScrollHeight);
        lastScrollHeight = sh;
        document.documentElement.scrollTop = sh;
      }
    }
    var myInterval = window.setInterval(autoScroll, 100);
}())

1 个答案:

答案 0 :(得分:0)

似乎您正在检查页面是否已经滚动,但从未取消过window.setInterval()

类似的东西应该可以工作:(未经测试)

(function() {
    var lastScrollHeight = 0, count = 0, myInterval = null, failCount = 0;
    function autoScroll() {
      count++;
      console.log(count);
      var sh = document.documentElement.scrollHeight;
      if (sh !== lastScrollHeight) {
        console.log(sh, lastScrollHeight);
        lastScrollHeight = sh;
        document.documentElement.scrollTop = sh;
        failCount = 0; // reset the number of failures
      }
      else {
        failCount++; // record that we failed
        if(failCount >= 10) // if we have failed 10 times in a row then exit
          window.clearInterval(myInterval);
      }
    }
    myInterval = window.setInterval(autoScroll, 100);
}())

编辑: 更新为允许10个循环,在退出间隔之前没有滚动。

相关问题