网页快照截图

45 阅读1分钟

分享网页快照截图代码

const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs');

/**
 * 网页全快照截取函数(使用fullPage模式)
 * @param {string} targetUrl - 目标网页的 URL
 * @param {string} savePath - 保存的文件夹路径
 * @param {string} fileName - 保存的文件名
 */
async function takeFullScreenshot(targetUrl, savePath, fileName) {
    // 1. 处理保存路径
    if (!fs.existsSync(savePath)) {
        fs.mkdirSync(savePath, { recursive: true });
        console.log(`已创建目录: ${savePath}`);
    }

    const finalFilePath = path.join(savePath, fileName);

    console.log('🚀 正在启动浏览器...');
    const browser = await puppeteer.launch({
        headless: "new",
        executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-gpu',
            '--no-zygote',
            '--disable-software-rasterizer'
        ],
        ignoreHTTPSErrors: true,
        timeout: 60000
    });

    try {
        const page = await browser.newPage();

        console.log(`🌐 正在打开页面: ${targetUrl}`);
        await page.goto(targetUrl, {
            waitUntil: 'networkidle2',
            timeout: 120000
        });

        // 2. 设置合理的视口宽度
        console.log('🖥️ 设置视口...');
        await page.setViewport({ width: 1200, height: 800 });

        // 3. 等待页面稳定
        console.log('⏳ 等待页面渲染稳定...');
        await new Promise(resolve => setTimeout(resolve, 2000));

        // 4. 执行完整页面截图(fullPage模式)
        console.log('📸 正在生成完整网页快照...');
        await page.screenshot({
            path: finalFilePath,
            fullPage: true,
            type: 'png'
        });

        console.log(`\n✅ 成功!快照已保存至: ${finalFilePath}`);

    } catch (error) {
        console.error('❌ 截图过程中出现错误:', error);
    } finally {
        await browser.close();
        console.log('浏览器已关闭。');
    }
}

// ========================================================
//                     用户配置区
// ========================================================

const config = {
    // 目标 URL
    url: 'https://baike.baidu.com/item/%E9%95%BF%E6%B2%99%E5%B8%82/12020819?fromtitle=%E9%95%BF%E6%B2%99&fromid=204237',
      
    // 保存的本地文件夹路径
    saveDir: 'E:\\py_project\\temp\\res',   
      
    // 保存的文件名
    fileName: '1.png'
};

// 执行主程序
takeFullScreenshot(config.url, config.saveDir, config.fileName).catch(console.error);

结果示例:

image.png

2.png