Skip to main content

BrowserType

BrowserType 提供了启动特定浏览器实例或连接到现有浏览器实例的方法。以下是使用 Playwright 驱动自动化的典型示例:

¥BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is a typical example of using Playwright to drive automation:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// other actions...
await browser.close();
})();

方法

¥Methods

connect

Added before v1.9 browserType.connect

此方法将 Playwright 附加到现有浏览器实例。当连接到 Node.js 中通过 BrowserType.launchServer 启动的另一个浏览器时,主版本和次版本需要与客户端版本匹配(1.2.3 → 兼容 1.2.x)。

¥This method attaches Playwright to an existing browser instance. When connecting to another browser launched via BrowserType.launchServer in Node.js, the major and minor version needs to match the client version (1.2.3 → is compatible with 1.2.x).

用法

¥Usage

await browserType.connect(wsEndpoint);
await browserType.connect(wsEndpoint, options);

参数

¥Arguments

  • wsEndpoint string Added in: v1.10#

要连接的浏览器 Websocket 端点。

¥A browser websocket endpoint to connect to.

  • options Object (optional)

    • exposeNetwork string (optional) Added in: v1.37#

此选项将连接客户端上可用的网络公开给正在连接的浏览器。由逗号分隔的规则列表组成。

¥This option exposes network available on the connecting client to the browser being connected to. Consists of a list of rules separated by comma.

可用规则:

¥Available rules:

  1. 主机名模式,例如:example.com*.org:99x.*.y.com*foo.org

    ¥Hostname pattern, for example: example.com, *.org:99, x.*.y.com, *foo.org.

  2. IP 字面量,例如:127.0.0.10.0.0.0:99[::1][0:0::1]:99

    ¥IP literal, for example: 127.0.0.1, 0.0.0.0:99, [::1], [0:0::1]:99.

  3. 匹配本地环回接口的 <loopback>localhost*.localhost127.0.0.1[::1]

    ¥<loopback> that matches local loopback interfaces: localhost, *.localhost, 127.0.0.1, [::1].

一些常见的例子:

¥Some common examples:

  1. "*" 暴露所有网络。

    ¥"*" to expose all network.

  2. "<loopback>" 暴露本地主机网络。

    ¥"<loopback>" to expose localhost network.

  3. "*.test.internal-domain,*.staging.internal-domain,<loopback>" 公开测试/暂存部署和本地主机。

    ¥"*.test.internal-domain,*.staging.internal-domain,<loopback>" to expose test/staging deployments and localhost.

与 Web 套接字连接请求一起发送的附加 HTTP 标头。可选的。

¥Additional HTTP headers to be sent with web socket connect request. Optional.

  • logger Logger (optional) Added in: v1.14#

用于 Playwright 日志记录的日志器接收器。可选的。

¥Logger sink for Playwright logging. Optional.

  • slowMo number (optional) Added in: v1.10#

将 Playwright 操作减慢指定的毫秒数。很有用,这样你就可以看到发生了什么。默认为 0。

¥Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.

  • timeout number (optional) Added in: v1.10#

等待建立连接的最长时间(以毫秒为单位)。默认为 0(无超时)。

¥Maximum time in milliseconds to wait for the connection to be established. Defaults to 0 (no timeout).

返回

¥Returns


connectOverCDP

Added in: v1.9 browserType.connectOverCDP

此方法使用 Chrome DevTools 协议将 Playwright 附加到现有浏览器实例。

¥This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.

默认浏览器上下文可通过 browser.contexts() 访问。

¥The default browser context is accessible via browser.contexts().

注意

仅基于 Chromium 的浏览器支持通过 Chrome DevTools 协议进行连接。

¥Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.

用法

¥Usage

const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
const defaultContext = browser.contexts()[0];
const page = defaultContext.pages()[0];

参数

¥Arguments

  • endpointURL string Added in: v1.11#

要连接的 CDP websocket 端点或 http url。例如 http://localhost:9222/ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4

¥A CDP websocket endpoint or http url to connect to. For example http://localhost:9222/ or ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4.

  • options Object (optional)

    • endpointURL string (optional) Added in: v1.14#

已弃用,请改用第一个参数。可选的。

¥Deprecated, use the first argument instead. Optional.

与连接请求一起发送的附加 HTTP 标头。可选的。

¥Additional HTTP headers to be sent with connect request. Optional.

  • logger Logger (optional) Added in: v1.14#

用于 Playwright 日志记录的日志器接收器。可选的。

¥Logger sink for Playwright logging. Optional.

  • slowMo number (optional) Added in: v1.11#

将 Playwright 操作减慢指定的毫秒数。很有用,这样你就可以看到发生了什么。默认为 0。

¥Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.

  • timeout number (optional) Added in: v1.11#

等待建立连接的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Maximum time in milliseconds to wait for the connection to be established. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


executablePath

Added before v1.9 browserType.executablePath

Playwright 希望找到打包的浏览器可执行文件的路径。

¥A path where Playwright expects to find a bundled browser executable.

用法

¥Usage

browserType.executablePath();

返回

¥Returns


launch

Added before v1.9 browserType.launch

返回浏览器实例。

¥Returns the browser instance.

用法

¥Usage

你可以使用 ignoreDefaultArgs 从默认参数中过滤掉 --mute-audio

¥You can use ignoreDefaultArgs to filter out --mute-audio from default arguments:

const browser = await chromium.launch({  // Or 'firefox' or 'webkit'.
ignoreDefaultArgs: ['--mute-audio']
});

仅限 Chromium 的 Playwright 还可用于控制 Google Chrome 或 Microsoft Edge 浏览器,但它与打包的 Chromium 版本配合使用效果最佳。不保证它可以与任何其他版本一起使用。使用 executablePath 选项时要格外小心。

¥Chromium-only Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use executablePath option with extreme caution.

如果首选 Google Chrome(而不是 Chromium),建议使用 Chrome Canary开发通道 版本。

¥If Google Chrome (rather than Chromium) is preferred, a Chrome Canary or Dev Channel build is suggested.

Google Chrome 和 Microsoft Edge 等普通浏览器适合需要专有媒体编解码器进行视频播放的测试。有关 Chromium 和 Chrome 之间的其他差异,请参阅 本文本文 描述了 Linux 用户的一些差异。

¥Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs for video playback. See this article for other differences between Chromium and Chrome. This article describes some differences for Linux users.

参数

¥Arguments

警告

使用自定义浏览器参数需要你自担风险,因为其中一些参数可能会破坏 Playwright 功能。:::

¥Use custom browser args at your own risk, as some of them may break Playwright functionality.

要传递给浏览器实例的其他参数。Chromium 标志列表可以在 此处 中找到。

¥Additional arguments to pass to the browser instance. The list of Chromium flags can be found here.

浏览器分发渠道。

¥Browser distribution channel.

使用 "chromium" 到 选择加入新的无头模式

¥Use "chromium" to opt in to new headless mode.

使用 "chrome"、"chrome-beta"、"chrome-dev"、"chrome-canary"、"msedge"、"msedge-beta"、"msedge-dev" 或 "msedge-canary" 来使用品牌 谷歌浏览器和微软 Edge

¥Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded Google Chrome and Microsoft Edge.

启用 Chromium 沙箱。默认为 false

¥Enable Chromium sandboxing. Defaults to false.

Deprecated

Use debugging tools instead.

Chromium-only 是否为每个选项卡自动打开开发者工具面板。如果此选项为 true,则 headless 选项将设置为 false

¥Chromium-only Whether to auto-open a Developer Tools panel for each tab. If this option is true, the headless option will be set false.

如果指定,接受的下载将下载到此目录中。否则,将创建临时目录,并在浏览器关闭时将其删除。无论哪种情况,当创建下载的浏览器上下文关闭时,下载都会被删除。

¥If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed.

指定浏览器可见的环境变量。默认为 process.env

¥Specify environment variables that will be visible to the browser. Defaults to process.env.

  • executablePath string (optional)#

要运行的浏览器可执行文件(而不是打包的可执行文件)的路径。如果 executablePath 是相对路径,则相对于当前工作目录进行解析。请注意,Playwright 仅适用于打包的 Chromium、Firefox 或 WebKit,使用风险由你自行承担。

¥Path to a browser executable to run instead of the bundled one. If executablePath is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.

火狐用户偏好。在 about:config 了解有关 Firefox 用户首选项的更多信息。

¥Firefox user preferences. Learn more about the Firefox user preferences at about:config.

在 SIGHUP 上关闭浏览器进程。默认为 true

¥Close the browser process on SIGHUP. Defaults to true.

按 Ctrl-C 关闭浏览器进程。默认为 true

¥Close the browser process on Ctrl-C. Defaults to true.

在 SIGTERM 上关闭浏览器进程。默认为 true

¥Close the browser process on SIGTERM. Defaults to true.

是否以无头模式运行浏览器。Chromium火狐浏览器 的更多详细信息。默认为 true,除非 devtools 选项为 true

¥Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to true unless the devtools option is true.

如果是 true,Playwright 不会传递自己的配置参数,而仅使用 args 中的配置参数。如果给出了一个数组,则过滤掉给定的默认参数。危险的选择;小心使用。默认为 false

¥If true, Playwright does not pass its own configurations args and only uses the ones from args. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to false.

用于 Playwright 日志记录的日志器接收器。

¥Logger sink for Playwright logging.

用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128socks5://myproxy.com:3128。缩写形式 myproxy.com:3128 被视为 HTTP 代理。

¥Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.

用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"

¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

如果 HTTP 代理需要身份验证,则使用可选的用户名。

¥Optional username to use if HTTP proxy requires authentication.

如果 HTTP 代理需要身份验证,则使用可选密码。

¥Optional password to use if HTTP proxy requires authentication.

网络代理设置。

¥Network proxy settings.

将 Playwright 操作减慢指定的毫秒数。很有用,这样你就可以看到发生了什么。

¥Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.

等待浏览器实例启动的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Maximum time in milliseconds to wait for the browser instance to start. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

如果指定,跟踪将保存到此目录中。

¥If specified, traces are saved into this directory.

返回

¥Returns


launchPersistentContext

Added before v1.9 browserType.launchPersistentContext

返回持久浏览器上下文实例。

¥Returns the persistent browser context instance.

启动使用位于 userDataDir 的持久存储的浏览器并返回唯一的上下文。关闭此上下文将自动关闭浏览器。

¥Launches browser that uses persistent storage located at userDataDir and returns the only context. Closing this context will automatically close the browser.

用法

¥Usage

await browserType.launchPersistentContext(userDataDir);
await browserType.launchPersistentContext(userDataDir, options);

参数

¥Arguments

用户数据目录的路径,该目录存储浏览器会话数据,例如 cookie 和本地存储。Chromium火狐浏览器 的更多详细信息。请注意,Chromium 的用户数据目录是 chrome://version 处看到的 "轮廓路径" 的父目录。传递一个空字符串以使用临时目录。

¥Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for Chromium and Firefox. Note that Chromium's user data directory is the parent directory of the "Profile Path" seen at chrome://version. Pass an empty string to use a temporary directory instead.

是否自动下载所有附件。默认为 true,接受所有下载。

¥Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.

警告

使用自定义浏览器参数需要你自担风险,因为其中一些参数可能会破坏 Playwright 功能。:::

¥Use custom browser args at your own risk, as some of them may break Playwright functionality.

要传递给浏览器实例的其他参数。Chromium 标志列表可以在 此处 中找到。

¥Additional arguments to pass to the browser instance. The list of Chromium flags can be found here.

当使用 page.goto()page.route()page.waitForURL()page.waitForRequest()page.waitForResponse() 时,它会使用 URL() 构造函数来构建相应的 URL,从而考虑基本 URL。默认情况下取消设置。示例:

¥When using page.goto(), page.route(), page.waitForURL(), page.waitForRequest(), or page.waitForResponse() it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:

  • baseURL:http://localhost:3000 并导航至 /bar.html 结果为 http://localhost:3000/bar.html

    ¥baseURL: http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html

  • baseURL:http://localhost:3000/foo/ 并导航至 ./bar.html 结果为 http://localhost:3000/foo/bar.html

    ¥baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html

  • baseURL:http://localhost:3000/foo(无尾部斜杠)并导航至 ./bar.html 将导致 http://localhost:3000/bar.html

    ¥baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html

切换绕过页面的内容安全策略。默认为 false

¥Toggles bypassing page's Content-Security-Policy. Defaults to false.

浏览器分发渠道。

¥Browser distribution channel.

使用 "chromium" 到 选择加入新的无头模式

¥Use "chromium" to opt in to new headless mode.

使用 "chrome"、"chrome-beta"、"chrome-dev"、"chrome-canary"、"msedge"、"msedge-beta"、"msedge-dev" 或 "msedge-canary" 来使用品牌 谷歌浏览器和微软 Edge

¥Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded Google Chrome and Microsoft Edge.

启用 Chromium 沙箱。默认为 false

¥Enable Chromium sandboxing. Defaults to false.

证书有效的确切来源。Origin 包括 https 协议、主机名和可选的端口。

¥Exact origin that the certificate is valid for. Origin includes https protocol, a hostname and optionally a port.

PEM 格式的证书文件路径。

¥Path to the file with the certificate in PEM format.

PEM 格式的证书的直接值。

¥Direct value of the certificate in PEM format.

PEM 格式的私钥文件路径。

¥Path to the file with the private key in PEM format.

PEM 格式的私钥的直接值。

¥Direct value of the private key in PEM format.

PFX 或 PKCS12 编码的私钥和证书链的路径。

¥Path to the PFX or PKCS12 encoded private key and certificate chain.

PFX 或 PKCS12 编码的私钥和证书链的直接值。

¥Direct value of the PFX or PKCS12 encoded private key and certificate chain.

  • passphrase string (optional)

私钥的密码(PEM 或 PFX)。

¥Passphrase for the private key (PEM or PFX).

TLS 客户端身份验证允许服务器请求客户端证书并对其进行验证。

¥TLS Client Authentication allows the server to request a client certificate and verify it.

细节

¥Details

要使用的客户端证书数组。每个证书对象必须同时具有 certPathkeyPath、单个 pfxPath 或它们对应的直接值等价物(certkeypfx)。如果证书已加密,则可选地提供 passphrase 属性。origin 属性应与证书有效的请求来源完全匹配。

¥An array of client certificates to be used. Each certificate object must have either both certPath and keyPath, a single pfxPath, or their corresponding direct value equivalents (cert and key, or pfx). Optionally, passphrase property should be provided if the certificate is encrypted. The origin property should be provided with an exact match to the request origin that the certificate is valid for.

注意

在 macOS 上使用 WebKit 时,访问 localhost 将不会获取客户端证书。你可以通过将 localhost 替换为 local.playwright 来使其工作。:::

¥When using WebKit on macOS, accessing localhost will not pick up client certificates. You can make it work by replacing localhost with local.playwright.

  • colorScheme null | "light" | "dark" | "no-preference" (optional)#

模拟 prefers-colors-scheme 媒体功能,支持的值为 'light''dark'。详细信息请参见 page.emulateMedia()。传递 null 会将模拟重置为系统默认值。默认为 'light'

¥Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'light'.

  • deviceScaleFactor number (optional)#

指定设备比例因子(可以视为 dpr)。默认为 1。了解有关 使用设备比例因子模拟设备 的更多信息。

¥Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.

Deprecated

Use debugging tools instead.

Chromium-only 是否为每个选项卡自动打开开发者工具面板。如果此选项为 true,则 headless 选项将设置为 false

¥Chromium-only Whether to auto-open a Developer Tools panel for each tab. If this option is true, the headless option will be set false.

如果指定,接受的下载将下载到此目录中。否则,将创建临时目录,并在浏览器关闭时将其删除。无论哪种情况,当创建下载的浏览器上下文关闭时,下载都会被删除。

¥If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed.

指定浏览器可见的环境变量。默认为 process.env

¥Specify environment variables that will be visible to the browser. Defaults to process.env.

  • executablePath string (optional)#

要运行的浏览器可执行文件(而不是打包的可执行文件)的路径。如果 executablePath 是相对路径,则相对于当前工作目录进行解析。请注意,Playwright 仅适用于打包的 Chromium、Firefox 或 WebKit,使用风险由你自行承担。

¥Path to a browser executable to run instead of the bundled one. If executablePath is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.

包含随每个请求发送的附加 HTTP 标头的对象。默认为无。

¥An object containing additional HTTP headers to be sent with every request. Defaults to none.

火狐用户偏好。在 about:config 了解有关 Firefox 用户首选项的更多信息。

¥Firefox user preferences. Learn more about the Firefox user preferences at about:config.

  • forcedColors null | "active" | "none" (optional)#

模拟 'forced-colors' 媒体功能,支持的值为 'active''none'。详细信息请参见 page.emulateMedia()。传递 null 会将模拟重置为系统默认值。默认为 'none'

¥Emulates 'forced-colors' media feature, supported values are 'active', 'none'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'none'.

纬度在 -90 到 90 之间。

¥Latitude between -90 and 90.

经度在 -180 到 180 之间。

¥Longitude between -180 and 180.

非负精度值。默认为 0

¥Non-negative accuracy value. Defaults to 0.

在 SIGHUP 上关闭浏览器进程。默认为 true

¥Close the browser process on SIGHUP. Defaults to true.

按 Ctrl-C 关闭浏览器进程。默认为 true

¥Close the browser process on Ctrl-C. Defaults to true.

在 SIGTERM 上关闭浏览器进程。默认为 true

¥Close the browser process on SIGTERM. Defaults to true.

指定视口是否支持触摸事件。默认为 false。了解有关 移动模拟 的更多信息。

¥Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.

是否以无头模式运行浏览器。Chromium火狐浏览器 的更多详细信息。默认为 true,除非 devtools 选项为 true

¥Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to true unless the devtools option is true.

限制在特定来源 (scheme://host:port) 上发送 http 凭据。

¥Restrain sending http credentials on specific origin (scheme://host:port).

  • send "unauthorized" | "always"(可选)

    ¥send "unauthorized" | "always" (optional)

    此选项仅适用于从相应 APIRequestContext 发送的请求,不影响从浏览器发送的请求。'always' - 带有基本身份验证凭据的 Authorization 标头将随每个 API 请求一起发送。'unauthorized - 仅当收到带有 WWW-Authenticate 标头的 401(未授权)响应时才会发送凭据。默认为 'unauthorized'

    ¥This option only applies to the requests sent from corresponding APIRequestContext and does not affect requests sent from the browser. 'always' - Authorization header with basic authentication credentials will be sent with the each API request. 'unauthorized - the credentials are only sent when 401 (Unauthorized) response with WWW-Authenticate header is received. Defaults to 'unauthorized'.

HTTP 认证 的凭证。如果未指定来源,则用户名和密码将在未经授权的响应时发送到任何服务器。

¥Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

如果是 true,Playwright 不会传递自己的配置参数,而仅使用 args 中的配置参数。如果给出了一个数组,则过滤掉给定的默认参数。危险的选择;小心使用。默认为 false

¥If true, Playwright does not pass its own configurations args and only uses the ones from args. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to false.

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

是否考虑 meta viewport 标签并启用触摸事件。isMobile 是设备的一部分,因此你实际上不需要手动设置它。默认为 false,Firefox 不支持。了解有关 移动模拟 的更多信息。

¥Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false and is not supported in Firefox. Learn more about mobile emulation.

是否在上下文中启用 JavaScript。默认为 true。了解有关 禁用 JavaScript 的更多信息。

¥Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.

指定用户区域设置,例如 en-GBde-DE 等。区域设置会影响 navigator.language 值、Accept-Language 请求标头值以及数字和日期格式规则。默认为系统默认区域设置。在我们的 模拟指南 中了解有关模拟的更多信息。

¥Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. Defaults to the system default locale. Learn more about emulation in our emulation guide.

用于 Playwright 日志记录的日志器接收器。

¥Logger sink for Playwright logging.

是否模拟网络离线。默认为 false。了解有关 网络模拟 的更多信息。

¥Whether to emulate network being offline. Defaults to false. Learn more about network emulation.

授予此上下文中所有页面的权限列表。详细信息请参见 browserContext.grantPermissions()。默认为无。

¥A list of permissions to grant to all pages in this context. See browserContext.grantPermissions() for more details. Defaults to none.

用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128socks5://myproxy.com:3128。缩写形式 myproxy.com:3128 被视为 HTTP 代理。

¥Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.

用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"

¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

如果 HTTP 代理需要身份验证,则使用可选的用户名。

¥Optional username to use if HTTP proxy requires authentication.

如果 HTTP 代理需要身份验证,则使用可选密码。

¥Optional password to use if HTTP proxy requires authentication.

网络代理设置。

¥Network proxy settings.

用于控制是否省略 HAR 中的请求内容的可选设置。默认为 false。已弃用,请改用 content 策略。

¥Optional setting to control whether to omit request content from the HAR. Defaults to false. Deprecated, use content policy instead.

  • content "omit" | "embed" | "attach"(可选)

    ¥content "omit" | "embed" | "attach" (optional)

    用于控制资源内容管理的可选设置。如果指定了 omit,则不会保留内容。如果指定了 attach,资源将作为单独的文件或条目保留在 ZIP 存档中。如果指定了 embed,则根据 HAR 规范将内容内联存储在 HAR 文件中。对于 .zip 输出文件,默认为 attach;对于所有其他文件扩展名,默认为 embed

    ¥Optional setting to control resource content management. If omit is specified, content is not persisted. If attach is specified, resources are persisted as separate files or entries in the ZIP archive. If embed is specified, content is stored inline the HAR file as per HAR specification. Defaults to attach for .zip output files and to embed for all other file extensions.

将 HAR 文件写入到的文件系统上的路径。如果文件名以 .zip 结尾,则默认使用 content: 'attach'

¥Path on the filesystem to write the HAR file to. If the file name ends with .zip, content: 'attach' is used by default.

  • mode "full" | "minimal"(可选)

    ¥mode "full" | "minimal" (optional)

    当设置为 minimal 时,仅记录从 HAR 路由所需的信息。这会忽略从 HAR 重放时不使用的大小、计时、页面、cookie、安全性和其他类型的 HAR 信息。默认为 full

    ¥When set to minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to full.

用于过滤存储在 HAR 中的请求的 glob 或正则表达式模式。当通过上下文选项提供 baseURL 并且传递的 URL 是路径时,它将通过 new URL() 构造函数合并。默认为无。

¥A glob or regex pattern to filter requests that are stored in the HAR. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor. Defaults to none.

启用所有页面的 HAR 记录到 recordHar.path 文件中。如果未指定,则不会记录 HAR。确保等待 browserContext.close() 才能保存 HAR。

¥Enables HAR recording for all pages into recordHar.path file. If not specified, the HAR is not recorded. Make sure to await browserContext.close() for the HAR to be saved.

放置视频的目录路径。

¥Path to the directory to put videos into.

视频帧宽度。

¥Video frame width.

视频帧高度。

¥Video frame height.

录制视频的可选尺寸。如果未指定,大小将等于 viewport 缩小以适合 800x800。如果未明确配置 viewport,则视频大小默认为 800x450。如有必要,每页的实际图片将按比例缩小以适合指定的尺寸。

¥Optional dimensions of the recorded videos. If not specified the size will be equal to viewport scaled down to fit into 800x800. If viewport is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.

启用 recordVideo.dir 目录中所有页面的视频录制。如果未指定,则不会录制视频。请务必等待 browserContext.close() 才能保存视频。

¥Enables video recording for all pages into recordVideo.dir directory. If not specified videos are not recorded. Make sure to await browserContext.close() for videos to be saved.

  • reducedMotion null | "reduce" | "no-preference" (optional)#

模拟 'prefers-reduced-motion' 媒体功能,支持的值为 'reduce''no-preference'。详细信息请参见 page.emulateMedia()。传递 null 会将模拟重置为系统默认值。默认为 'no-preference'

¥Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'no-preference'.

页面宽度(以像素为单位)。

¥page width in pixels.

页面高度(以像素为单位)。

¥page height in pixels.

通过 window.screen 模拟网页内可用的一致窗口屏幕尺寸。仅当设置了 viewport 时才使用。

¥Emulates consistent window screen size available inside web page via window.screen. Is only used when the viewport is set.

  • serviceWorkers "allow" | "block"(可选)#

    ¥serviceWorkers "allow" | "block" (optional)#

    是否允许站点注册 Service Worker。默认为 'allow'

    ¥Whether to allow sites to register Service workers. Defaults to 'allow'.

    • 'allow'服务工作进程 可以注册。

      ¥'allow': Service Workers can be registered.

    • 'block':Playwright 将阻止所有服务工作进程的注册。

      ¥'block': Playwright will block all registration of Service Workers.

将 Playwright 操作减慢指定的毫秒数。很有用,这样你就可以看到发生了什么。

¥Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.

如果设置为 true,则为此上下文启用严格选择器模式。在严格选择器模式下,当多个元素与选择器匹配时,所有暗示单个目标 DOM 元素的选择器操作都会抛出异常。此选项不会影响任何定位器 API(定位器始终是严格的)。默认为 false。请参阅 Locator 了解有关严格模式的更多信息。

¥If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors that imply single target DOM element will throw when more than one element matches the selector. This option does not affect any Locator APIs (Locators are always strict). Defaults to false. See Locator to learn more about the strict mode.

等待浏览器实例启动的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Maximum time in milliseconds to wait for the browser instance to start. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

更改上下文的时区。有关支持的时区 ID 的列表,请参阅 ICU 的 metaZones.txt。默认为系统时区。

¥Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.

如果指定,跟踪将保存到此目录中。

¥If specified, traces are saved into this directory.

在此上下文中使用的特定用户代理。

¥Specific user agent to use in this context.

Deprecated

Use recordVideo instead.

视频帧宽度。

¥Video frame width.

视频帧高度。

¥Video frame height.

Deprecated

Use recordVideo instead.

页面宽度(以像素为单位)。

¥page width in pixels.

页面高度(以像素为单位)。

¥page height in pixels.

模拟每个页面的一致视口。默认为 1280x720 视口。使用 null 禁用一致视口模拟。了解有关 视口模拟 的更多信息。

¥Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use null to disable the consistent viewport emulation. Learn more about viewport emulation.

注意

null 值从默认预设中选择退出,使视口取决于操作系统定义的主机窗口大小。它使得测试的执行具有不确定性。:::

¥The null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic.

返回

¥Returns


launchServer

Added before v1.9 browserType.launchServer

返回浏览器应用实例。你可以通过 browserType.connect() 连接到它,这需要主要/次要客户端/服务器版本匹配(1.2.3 → 与 1.2.x 兼容)。

¥Returns the browser app instance. You can connect to it via browserType.connect(), which requires the major/minor client/server version to match (1.2.3 → is compatible with 1.2.x).

用法

¥Usage

启动客户端可以连接的浏览器服务器。启动浏览器可执行文件并稍后连接到它的示例:

¥Launches browser server that client can connect to. An example of launching a browser executable and connecting to it later:

const { chromium } = require('playwright');  // Or 'webkit' or 'firefox'.

(async () => {
const browserServer = await chromium.launchServer();
const wsEndpoint = browserServer.wsEndpoint();
// Use web socket endpoint later to establish a connection.
const browser = await chromium.connect(wsEndpoint);
// Close browser instance.
await browserServer.close();
})();

参数

¥Arguments

警告

使用自定义浏览器参数需要你自担风险,因为其中一些参数可能会破坏 Playwright 功能。:::

¥Use custom browser args at your own risk, as some of them may break Playwright functionality.

要传递给浏览器实例的其他参数。Chromium 标志列表可以在 此处 中找到。

¥Additional arguments to pass to the browser instance. The list of Chromium flags can be found here.

浏览器分发渠道。

¥Browser distribution channel.

使用 "chromium" 到 选择加入新的无头模式

¥Use "chromium" to opt in to new headless mode.

使用 "chrome"、"chrome-beta"、"chrome-dev"、"chrome-canary"、"msedge"、"msedge-beta"、"msedge-dev" 或 "msedge-canary" 来使用品牌 谷歌浏览器和微软 Edge

¥Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded Google Chrome and Microsoft Edge.

启用 Chromium 沙箱。默认为 false

¥Enable Chromium sandboxing. Defaults to false.

Deprecated

Use debugging tools instead.

Chromium-only 是否为每个选项卡自动打开开发者工具面板。如果此选项为 true,则 headless 选项将设置为 false

¥Chromium-only Whether to auto-open a Developer Tools panel for each tab. If this option is true, the headless option will be set false.

如果指定,接受的下载将下载到此目录中。否则,将创建临时目录,并在浏览器关闭时将其删除。无论哪种情况,当创建下载的浏览器上下文关闭时,下载都会被删除。

¥If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed.

指定浏览器可见的环境变量。默认为 process.env

¥Specify environment variables that will be visible to the browser. Defaults to process.env.

  • executablePath string (optional)#

要运行的浏览器可执行文件(而不是打包的可执行文件)的路径。如果 executablePath 是相对路径,则相对于当前工作目录进行解析。请注意,Playwright 仅适用于打包的 Chromium、Firefox 或 WebKit,使用风险由你自行承担。

¥Path to a browser executable to run instead of the bundled one. If executablePath is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.

火狐用户偏好。在 about:config 了解有关 Firefox 用户首选项的更多信息。

¥Firefox user preferences. Learn more about the Firefox user preferences at about:config.

在 SIGHUP 上关闭浏览器进程。默认为 true

¥Close the browser process on SIGHUP. Defaults to true.

按 Ctrl-C 关闭浏览器进程。默认为 true

¥Close the browser process on Ctrl-C. Defaults to true.

在 SIGTERM 上关闭浏览器进程。默认为 true

¥Close the browser process on SIGTERM. Defaults to true.

是否以无头模式运行浏览器。Chromium火狐浏览器 的更多详细信息。默认为 true,除非 devtools 选项为 true

¥Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to true unless the devtools option is true.

  • host string (optional) Added in: v1.45#

用于 Web 套接字的主机。它是可选的,如果省略它,服务器将在 IPv6 可用时接受未指定的 IPv6 地址 (::) 上的连接,否则接受未指定的 IPv4 地址 (0.0.0.0) 上的连接。考虑通过选择特定接口来强化它。

¥Host to use for the web socket. It is optional and if it is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. Consider hardening it with picking a specific interface.

如果是 true,Playwright 不会传递自己的配置参数,而仅使用 args 中的配置参数。如果给出了一个数组,则过滤掉给定的默认参数。危险的选择;小心使用。默认为 false

¥If true, Playwright does not pass its own configurations args and only uses the ones from args. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to false.

用于 Playwright 日志记录的日志器接收器。

¥Logger sink for Playwright logging.

用于网络套接字的端口。默认为 0,选择任何可用端口。

¥Port to use for the web socket. Defaults to 0 that picks any available port.

用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128socks5://myproxy.com:3128。缩写形式 myproxy.com:3128 被视为 HTTP 代理。

¥Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.

用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"

¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

如果 HTTP 代理需要身份验证,则使用可选的用户名。

¥Optional username to use if HTTP proxy requires authentication.

如果 HTTP 代理需要身份验证,则使用可选密码。

¥Optional password to use if HTTP proxy requires authentication.

网络代理设置。

¥Network proxy settings.

等待浏览器实例启动的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Maximum time in milliseconds to wait for the browser instance to start. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

如果指定,跟踪将保存到此目录中。

¥If specified, traces are saved into this directory.

  • wsPath string (optional) Added in: v1.15#

为浏览器服务器提供服务的路径。为了安全起见,这默认为不可猜测的字符串。

¥Path at which to serve the Browser Server. For security, this defaults to an unguessable string.

警告

任何了解 wsPath 的进程或网页(包括在 Playwright 中运行的进程或网页)都可以控制操作系统用户。因此,使用此选项时应使用不可猜测的令牌。:::

¥Any process or web page (including those running in Playwright) with knowledge of the wsPath can take control of the OS user. For this reason, you should use an unguessable token when using this option.

返回

¥Returns


name

Added before v1.9 browserType.name

返回浏览器名称。例如:'chromium''webkit''firefox'

¥Returns browser name. For example: 'chromium', 'webkit' or 'firefox'.

用法

¥Usage

browserType.name();

返回

¥Returns