Windows与树莓派上Puppeteer截图TradingView的跨平台故障排查
问题场景
我用Puppeteer编写了TradingView页面截图代码,在Windows系统VSCode中运行完全正常,但部署到树莓派(Raspbian系统)后,无法发送带截图的消息,浏览器启动失败。
截图代码
const puppeteer = require('puppeteer'); async function captureChartScreenshot(symbol, interval) { const browser = await puppeteer.launch({ headless: "new" }); try { const page = await browser.newPage(); const chartUrl = `https://www.tradingview.com/chart/?symbol=${symbol}&interval=${interval}`; await page.goto(chartUrl); // 等待TradingView图表完全加载 await page.waitForSelector('.chart-gui-wrapper'); await page.setViewport({ width: 1200, height: 600, }); // 选择图表元素 const graficoElement = await page.$('.chart-container'); // 获取图表元素的尺寸 const graficoBoundingBox = await graficoElement.boundingBox(); // 仅截取图表元素的截图 const screenshotBuffer = await graficoElement.screenshot({ clip: { x: graficoBoundingBox.x, y: graficoBoundingBox.y, width: Math.min(graficoBoundingBox.width, page.viewport().width), height: Math.min(graficoBoundingBox.height, page.viewport().height), }, }); await browser.close(); return screenshotBuffer; } catch (error) { console.log(error); } }
报错信息
19/7/2023, 15:49:27
行错误:/home/pi/.cache/puppeteer/chrome/linux-114.0.5735.133/chrome-linux64/chrome: 1: /home/pi/.cache/puppeteer/chrome/linux-114.0.5735.133/chrome-linux64/chrome: 语法错误: "(" 意外
错误:启动浏览器进程失败!
/home/pi/.cache/puppeteer/chrome/linux-114.0.5735.133/chrome-linux64/chrome: 1: /home/pi/.cache/puppeteer/chrome/linux-114.0.5735.133/chrome-linux64/chrome: 语法错误: "(" 意外
已尝试的无效操作
- 查阅Puppeteer官方排障文档
- 重装NPM
- 更新Chrome版本
修复方案
1. 安装树莓派适配的Chromium
树莓派为ARM架构,Puppeteer默认下载的是x86_64版本Chrome,架构不兼容导致报错。先安装ARM版Chromium:
sudo apt update && sudo apt install chromium-browser chromium-codecs-ffmpeg
2. 修改Puppeteer启动配置
指定使用本地安装的ARM版Chromium,并添加无头环境必要的启动参数:
const browser = await puppeteer.launch({ headless: "new", executablePath: '/usr/bin/chromium-browser', // 本地Chromium路径 args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu', '--no-zygote' ] });
3. 清理无效缓存(可选)
删除Puppeteer缓存的x86版Chrome,避免冲突:
rm -rf /home/pi/.cache/puppeteer
4. 重新运行脚本
此时Puppeteer会调用适配ARM架构的Chromium,可正常启动并完成截图操作。
内容的提问来源于stack exchange,提问作者Manuel Verbo

