使用Puppeteer实现动态滚动加载内容的爬虫,你需要首先安装Puppeteer:
npm install puppeteer以下是一个简单的示例代码,用于模拟滚动加载动态内容:
const puppeteer = require('puppeteer');
 
async function crawlDynamicContent(url) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url, {waitUntil: 'networkidle2'});
 
    // 滚动到页面底部,触发动态加载
    await autoScroll(page);
 
    // 等待动态内容加载完成
    await page.waitFor(1000); // 根据实际情况设置等待时间
 
    // 保存页面内容或进行其他处理
    const content = await page.content();
    console.log(content);
 
    await browser.close();
}
 
async function autoScroll(page) {
    await page.evaluate(() => {
        return 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);
        });
    });
}
 
// 使用函数并传入目标网址
crawlDynamicContent('http://example.com');这段代码首先打开一个新页面,然后导航到指定的URL。waitUntil: 'networkidle2' 选项确保页面网络空闲时才继续执行脚本。autoScroll函数模拟滚动操作,通过不断增加scrollBy的调用来模拟滚动动作,直到页面底部。你可以根据实际情况调整滚动的距离和时间间隔。最后,你可以保存页面内容或进行其他处理。