Puppeteer - scroll down until you can#39;t anymore(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 - 向下滚动,直到你不能再
基础教程推荐
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01