Puppeteer 中文文档v25.8.0

Puppeteer

构建 npm puppeteer 包

Puppeteer 是一个 JavaScript 库,通过 DevTools 协议WebDriver BiDi提供高级 API 来控制 Chrome 或 Firefox。 Puppeteer 默认以无头(无可见界面)模式运行

快速开始 | API | FAQ | 贡献 | 故障排查

安装

npm i puppeteer # Downloads compatible Chrome during installation.
npm i puppeteer-core # Alternatively, install as a library, without downloading Chrome.
ℹ️注意

现代包管理器(包括 npm(参见 RFC)、pnpm、Yarn、Bun 和 Deno)默认阻止依赖安装脚本。如果安装脚本被阻止,Puppeteer 将不会在安装期间下载浏览器,从而导致运行时错误。

你可以在安装后手动下载所需的浏览器,运行:

npx puppeteer browsers install

或者,你可以配置包管理器以允许安装脚本运行(例如,对于 npm,在 package.json 中把 "puppeteer" 添加到 "allowScripts")。

MCP

安装 chrome-devtools-mcp,一个基于 Puppeteer 的 MCP 服务器,用于浏览器自动化与调试。

Puppeteer 还支持实验性的 WebMCP API。

示例

import puppeteer from 'puppeteer';
// Or import puppeteer from 'puppeteer-core';

// Launch the browser and open a new blank page.
const browser = await puppeteer.launch();
const page = await browser.newPage();

// Navigate the page to a URL.
await page.goto('https://developer.chrome.com/');

// Set the screen size.
await page.setViewport({width: 1080, height: 1024});

// Open the search menu using the keyboard.
await page.keyboard.press('/');

// Type into search box using accessible input name.
await page.locator('::-p-aria(Search)').fill('automate beyond recorder');

// Wait and click on first result.
await page.locator('.devsite-result-item-link').click();

// Locate the full title with a unique string.
const textSelector = await page
  .locator('::-p-text(Customize and automate)')
  .waitHandle();
const fullTitle = await textSelector?.evaluate(el => el.textContent);

// Print the full title.
console.log('The title of this blog post is "%s".', fullTitle);

await browser.close();