因工作需要使用无头浏览器,看了一下谷歌文档,尝试安装无头浏览器,地址是:developer.chrome.google.cn/docs/chromi…
其实步骤官网写的挺清楚的,我是自己一步一步尝试安装,一共搭建了2个环境的无头浏览器, window版本,liunx版本
window版本
检查是否有node环境
打开 cmd node -v
cmd npm -v
npm 安装太慢 映射一下淘宝的镜像
npm config set registry https://registry.npmmirror.com
验证是否成功
npm config get registry
如果输出结果是 https://registry.npmmirror.com/,则表示配置成功。
1、创建一个新的项目目录:
mkdir puppeteer-project
cd puppeteer-project
2、初始化 Node.js 项目:
npm init -y
3、 安装 Puppeteer
npm install puppeteer
如果觉得慢的话 可选择使用
yarn add puppeteer
注意:Puppeteer 会自动下载 Chromium 浏览器。如果你不需要 Chromium,可以使用 puppeteer-core,但需要手动安装浏览器。
linux版本
跟安装window版本差不多,但是liunx版本下载puppeteer非常慢,安装20分钟也没成功,所以我们选择使用puppeteer-core
npm install puppeteer-core
如果觉得慢的话 可选择使用
yarn add puppeteer-core
这个安装嗖嗖的....
下面是我下载好的谷歌浏览器
没发上传文件:google-chrome-stable-124.0.6367.118-1.x86_64.rpm
把文件上传到服务器上,检测依赖和安装
sudo rpm -ivh google-chrome-stable-124.0.6367.118-1.x86_64.rpm
安装完成以后 查找一下位置,有了位置就可以在编写代码中设置了
which google-chrome-stable
4、开始编写代码
// const puppeteer = require('puppeteer'); window版本
const puppeteer = require('puppeteer-core');
(async () => {
// 启动浏览器
console.log('开始打开浏览器');
const browser = await puppeteer.launch({
headless: true,
//executablePath: 'C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe', // 替换为你的浏览器路径
executablePath: "/usr/bin/google-chrome-stable",
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
// 打开一个新的页面
const page = await browser.newPage();
// 捕获失败的网络请求
page.on('requestfailed', (request) => {
console.log(`Failed request: ${request.url()}`);
});
console.log('开始打开指定页面');
let retries = 3;
while (retries > 0) {
try {
await page.goto('http://smart.yarward.com/human/index.html#/index10?id=8', {
waitUntil: 'networkidle0',
timeout: 60000, // 将超时时间设置为 60 秒
});
break;
} catch (error) {
console.log(`Failed to load page, retrying... (${retries} attempts left)`);
retries--;
}
}
// // 强制刷新页面
// await page.reload({
// waitUntil: 'networkidle0', // 等待网络空闲
// timeout: 60000, // 将超时时间设置为 60 秒
// });
// 等待页面完全加载
// await page.waitForNavigation({ waitUntil: 'networkidle0' });
await page.waitForSelector('#canvas-pic', { visible: true });
await page.waitForFunction(() => typeof window.webSdk.pictureHuman === 'function', { timeout: 60000 });
console.log('加载成功');
// 在页面上调用 window 上的方法
const result = await page.evaluate(() => {
// 假设页面中有一个 window.greet 方法
if (typeof window.webSdk === 'undefined') {
return 'window.webSdk is undefined';
}
if (typeof window.webSdk.pictureHuman !== 'function') {
return 'window.webSdk.pictureHuman is not a function';
}
let pcm2 = "https://star-light-lite.bj.bcebos.com/yinbintest/16k.pcm";
return window.webSdk.pictureHuman('1', '2', false, "/resource/pcms/464da23ec34a4be38a0d63fbf08112cb/7643e49023ee448aa1582a23cd997013.pcm", '是的冯绍峰防守打法收到发大水发杀佛是1');
});
console.log('Result from window method:', result);
// 设置等待时间(例如等待 10 秒)
await new Promise((resolve) => setTimeout(resolve, 60000)); // 10000 毫秒 = 10 秒
// 关闭浏览器
await browser.close();
})();