puppeteer 是一个 node.js 库,它提供了一个高级 api,用于通过 devtools 协议控制 chrome 或 chromium 浏览器。它是一个强大的工具,可用于网页抓取、自动化测试、捕获屏幕截图等。虽然在本地使用 puppeteer 很简单,但在服务器上运行它需要额外的考虑。本指南将引导您完成在服务器上启动并运行 puppeteer 的步骤。
为 puppeteer 准备服务器
更新服务器这一步对于puppeteer的成功执行至关重要。执行以下命令。
1
2
sudo apt update -y
sudo apt upgrade -y
安装以下依赖项以确保 puppeteer 顺利运行。
1
sudo apt-get install libpangocairo-1.0-0 libx11-xcb1 libxcomposite1 libxcursor1 libxdamage1 libxi6 libxtst6 libnss3 libcups2 libxss1 libxrandr2 libatk1.0-0 libgtk-3-0 libasound2t64
执行以下命令安装最新版本的 puppeteer,始终建议安装最新版本以获得最佳性能。
1
npm i puppeteer
使用傀儡师
您可以使用以下代码片段通过在您想要的路线调用此函数来验证 puppeteer 是否正常运行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const puppeteer = require("puppeteer");
/**
* Launches a Puppeteer browser, navigates to a webpage, and then closes the browser.
*
* Launch Options:
* - headless: Run the browser in headless mode (no GUI).
* - args:
* - "--no-sandbox": Required if running as the root user.
* - "--disable-setuid-sandbox": Optional, try if you encounter sandbox errors.
*/
const runPuppeteer = async () => {
try {
// Launch a Puppeteer browser instance with custom arguments
const browser = await puppeteer.launch({
headless: true,
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
],
});
// Open a new page in the browser
const page = await browser.newPage();
// Navigate to the specified URL
await page.goto("https://www.google.com");
console.log("Navigation to Google completed.");
// Close the browser
await browser.close();
console.log("Browser closed successfully.");
} catch (error) {
console.error("An error occurred:", error);
}
};
// Execute the function
runPuppeteer();
结论
在服务器上运行 puppeteer 需要仔细设置来处理依赖项、权限和资源。通过遵循本指南,您可以有效地部署 puppeteer 来执行服务器环境中的网页抓取或自动化测试等任务。对于更高级的用例,请考虑使用 pm2 等工具进行流程管理,使用 docker 进行容器化。
请随时与其他人分享本指南,如果您按照说明操作后遇到任何问题,请在评论中告诉我们。
以上就是在服务器上运行 Puppeteer:完整教程的详细内容,更多请关注php中文网其它相关文章!