Puppeteer - 向下滚动直到你不能再滚动 [英] Puppeteer - scroll down until you can't anymore

查看:29
本文介绍了Puppeteer - 向下滚动直到你不能再滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向下滚动时,我遇到了创建新内容的情况.新内容有一个特定的类名.

I am in a situation where new content is created when I scroll down. The new content has a specific class name.

如何继续向下滚动直到所有元素都加载完毕?

How can I keep scrolling down until all the elements have loaded?

换句话说,我想达到这样的阶段:如果我继续向下滚动,则不会加载任何新内容.

In other words, I want to reach the stage where if I keep scrolling down, nothing new will load.

我使用代码向下滚动,加上一个

I was using code to scroll down, coupled with an

await page.waitForSelector('.class_name');

这种方法的问题是在所有元素都加载后,代码继续向下滚动,没有创建新元素,最终我收到超时错误.

The problem with this approach is that after all the elements have loaded, the code keeps on scrolling down, no new elements are created and eventually I get a timeout error.

这是代码:

await page.evaluate( () => {
  window.scrollBy(0, window.innerHeight);
});
await page.waitForSelector('.class_name');

推荐答案

试试这个:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch({
        headless: false
    });
    const page = await browser.newPage();
    await page.goto('https://www.yoursite.com');
    await page.setViewport({
        width: 1200,
        height: 800
    });

    await autoScroll(page);

    await page.screenshot({
        path: 'yoursite.png',
        fullPage: true
    });

    await browser.close();
})();

async function autoScroll(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            var totalHeight = 0;
            var distance = 100;
            var timer = setInterval(() => {
                var scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

来源:https://github.com/chenxiaochun/blog/issues/38

这篇关于Puppeteer - 向下滚动直到你不能再滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆