[英]Scrape a page with 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);
}())
看起來好像您正在檢查頁面是否確實滾動,但從未取消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 個循環,在退出間隔之前不發生滾動。
這幾乎可以完美滿足我的需求。 當選項卡不是焦點選項卡時(AKA繼續在后台滾動),是否有辦法使它繼續工作?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.