Puppeteer - 向下滚动,直到你不能再

Puppeteer - scroll down until you can#39;t anymore(Puppeteer - 向下滚动,直到你不能再)

本文介绍了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 - 向下滚动,直到你不能再的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Puppeteer - 向下滚动,直到你不能再

基础教程推荐