部署
BotBrowser 无头模式下的截图最佳实践
在无头模式下使用 BotBrowser 捕获一致、高质量截图的实用指南。
概述
无头环境中的截图需要注意视口大小、页面加载时机和显示配置。BotBrowser 配置文件包含屏幕分辨率和设备像素比,使用 defaultViewport: null 保留这些值。
视口配置
const browser = await puppeteer.launch({
executablePath: '/path/to/botbrowser/chrome',
args: [
'--bot-profile=/path/to/profile.enc',
'--window-size=1920,1080',
],
headless: true,
defaultViewport: null,
});
页面加载时机
最常见的问题是捕获了部分加载的页面。使用正确的等待策略:
await page.goto('https://example.com', {
waitUntil: 'networkidle0',
timeout: 30000,
});
await page.waitForSelector('.main-content', { visible: true });
await page.evaluate(() => document.fonts.ready);
await page.screenshot({ path: 'output.png', fullPage: true });
截图格式
PNG 用于像素级精确。JPEG 配合 quality: 85 用于大批量处理。针对特定元素:
const element = await page.$('.target-element');
await element.screenshot({ path: 'element.png' });
Linux 上的 Xvfb
将虚拟显示与配置文件的分辨率匹配。使用 24 位色深:
Xvfb :10 -screen 0 1920x1080x24 &
export DISPLAY=:10.0
生产示例
const puppeteer = require('puppeteer-core');
async function captureScreenshot(url, outputPath) {
const browser = await puppeteer.launch({
executablePath: '/path/to/botbrowser/chrome',
args: [
'--bot-profile=/opt/profiles/profile.enc',
'--window-size=1920,1080',
],
headless: true,
defaultViewport: null,
});
try {
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
await page.screenshot({ path: outputPath, type: 'png' });
} finally {
await browser.close();
}
}
常见问题
空白截图:页面未加载完成。使用 waitUntil: 'networkidle0' 并添加显式等待。
视口尺寸错误:设置 defaultViewport: null。
缺失字体:在服务器上安装基础系统字体。
低分辨率:Xvfb 色深太低。使用 24 位色深。
#screenshot#headless#deployment#best-practices#production