如何在Puppeteer脚本中确定所使用的Chrome可执行文件路径?
如何在Puppeteer脚本内部确定当前使用的Chrome可执行文件路径?
问题场景
当使用Puppeteer启动浏览器时,无论是手动指定executablePath还是让Puppeteer自动查找默认浏览器,直接通过browser.executablePath都无法获取实际使用的路径:
// 指定executablePath的情况 const browser = await puppeteer.launch({ executablePath: '/path/to/chrome' }); // 未指定executablePath的情况 const browser = await puppeteer.launch(); // 以下代码无法正常工作 // console.log('executablePath is', browser.executablePath)
当未指定executablePath时,Puppeteer会自动查找系统默认浏览器:
- Windows系统默认路径通常为
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe - macOS和Linux系统会尝试读取PATH环境变量中的
chrome或chromium可执行文件
解决方案
方法1:从浏览器进程实例中获取实际路径
通过浏览器实例的process()方法获取对应的进程对象,其spawnfile属性会返回启动浏览器时使用的可执行文件路径,无论是否手动指定executablePath都能生效:
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); // 获取实际使用的浏览器路径 const actualExecutablePath = browser.process().spawnfile; console.log('当前Chrome可执行文件路径:', actualExecutablePath); await browser.close(); })();
方法2:获取Puppeteer自带浏览器的默认路径
如果使用的是Puppeteer预安装的Chrome/Chromium,可以直接调用puppeteer.executablePath()获取其默认路径,但注意这个方法不会返回手动指定的自定义路径:
const puppeteer = require('puppeteer'); // 获取Puppeteer自带浏览器的默认路径 const defaultPath = puppeteer.executablePath(); console.log('Puppeteer默认浏览器路径:', defaultPath); (async () => { const browser = await puppeteer.launch(); await browser.close(); })();
内容的提问来源于stack exchange,提问作者Alok
相关产品推荐
相关产品推荐

