Skip to main content
Version: 22.6.1

配置

¥Configuration

Puppeteer 中的所有默认设置都可以通过两种方式进行自定义:

¥All defaults in Puppeteer can be customized in two ways:

  1. 配置文件(推荐)

    ¥Configuration files (recommended)

  2. 环境变量

    ¥Environment variables

提醒

请注意,某些选项只能通过环境变量进行自定义(例如 HTTPS_PROXY)。

¥Note that some options are only customizable through environment variables (such as HTTPS_PROXY).

提醒

Puppeteer 的配置文件和环境变量被 puppeteer-core 忽略。

¥Puppeteer's configuration files and environment variables are ignored by puppeteer-core.

配置文件

¥Configuration files

配置文件是配置 Puppeteer 的推荐选择。Puppeteer 将在文件树中查找以下任何格式:

¥Configuration files are the recommended choice for configuring Puppeteer. Puppeteer will look up the file tree for any of the following formats:

  • .puppeteerrc.cjs,

  • .puppeteerrc.js,

  • .puppeteerrc(YAML/JSON),

  • .puppeteerrc.json,

  • .puppeteerrc.yaml,

  • puppeteer.config.js,和

    ¥puppeteer.config.js, and

  • puppeteer.config.cjs

Puppeteer 还会从应用的 package.json 中读取 puppeteer 密钥。

¥Puppeteer will also read a puppeteer key from your application's package.json.

有关可能的选项,请参阅 Configuration 接口。

¥See the Configuration interface for possible options.

提醒

添加配置文件后,如果更改影响安装,你可能需要删除并重新安装 puppeteer 才能使其生效。

¥After adding a configuration file, you may need to remove and reinstall puppeteer for it to take effect if the changes affect installation.

示例

¥Examples

更改默认缓存目录

¥Changing the default cache directory

从 v19.0.0 开始,Puppeteer 将浏览器存储在 ~/.cache/puppeteer 中,以便在安装之间全局缓存浏览器。如果 puppeteer 在某些构建步骤中被打包并移动到新位置,这可能会导致问题。以下配置可以解决该问题(重新安装 puppeteer 生效):

¥Starting in v19.0.0, Puppeteer stores browsers in ~/.cache/puppeteer to globally cache browsers between installation. This can cause problems if puppeteer is packed during some build step and moved to a fresh location. The following configuration can solve this issue (reinstall puppeteer to take effect):

project-directory/.puppeteerrc.cjs
const {join} = require('path');

/**

* @type {import("puppeteer").Configuration}
*/
module.exports = {
// Changes the cache location for Puppeteer.
cacheDirectory: join(__dirname, '.cache', 'puppeteer'),
};
注意

请注意,这仅适用于 CommonJS 配置文件,因为需要有关周围环境的信息(在本例中为 __dirname)。

¥Notice this is only possible with CommonJS configuration files as information about the ambient environment is needed (in this case, __dirname).

环境变量

¥Environment variables

除了配置文件之外,Puppeteer 还会查找某些 环境变量 来自定义行为。如果适用,环境变量将始终覆盖配置文件选项。

¥Along with configuration files, Puppeteer looks for certain environment variables for customizing behavior. Environment variables will always override configuration file options when applicable.

以下选项是仅环境选项

¥The following options are environment-only options

  • HTTP_PROXY, HTTPS_PROXY, NO_PROXY - 定义用于下载和运行浏览器的 HTTP 代理设置。

    ¥HTTP_PROXY, HTTPS_PROXY, NO_PROXY - defines HTTP proxy settings that are used to download and run the browser.

所有其他选项均可在 Configuration 接口的文档中找到。

¥All other options can be found in the documentation for the Configuration interface.