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 in: v1.8 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.

  • headers [Object]<[string], [string]> (optional) Added in: v1.11#

与 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

  • [Promise]<[Browser]>#

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.

  • headers [Object]<[string], [string]> (optional) Added in: v1.11#

与连接请求一起发送的附加 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

  • [Promise]<[Browser]>#

executablePath

Added in: v1.8 browserType.executablePath

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

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

用法

¥Usage

browserType.executablePath();

返回

¥Returns

  • [string]#

launch

Added in: v1.8 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

  • options [Object] (optional)

    • args [Array]<[string]> (optional)#
warning

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.

  • channel [string] (optional)#

浏览器分发渠道。支持的值为 "chrome"、"chrome-beta"、"chrome-dev"、"chrome-canary"、"msedge"、"msedge-beta"、"msedge-dev"、"msedge-canary"。了解有关使用 谷歌浏览器和微软 Edge 的更多信息。

¥Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using Google Chrome and Microsoft Edge.

  • chromiumSandbox [boolean] (optional)#

启用 Chromium 沙箱。默认为 false

¥Enable Chromium sandboxing. Defaults to false.

  • devtools [boolean] (optional)#
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.

  • downloadsPath [string] (optional)#

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

¥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.

  • env [Object]<[string], [string]|[number]|[boolean]> (optional)#

指定浏览器可见的环境变量。默认为 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.

  • firefoxUserPrefs [Object]<[string], [string]|[number]|[boolean]> (optional)#

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

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

  • handleSIGHUP [boolean] (optional)#

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

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

  • handleSIGINT [boolean] (optional)#

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

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

  • handleSIGTERM [boolean] (optional)#

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

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

  • headless [boolean] (optional)#

是否以无头模式运行浏览器。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.

  • ignoreDefaultArgs [boolean]|[Array]<[string]> (optional)#

如果是 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.

  • logger [Logger] (optional)#

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

¥Logger sink for Playwright logging.

  • proxy [Object] (optional)#

    • server [string]

用于所有请求的代理。支持 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.

  • bypass [string] (optional)

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

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

  • username [string] (optional)

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

¥Optional username to use if HTTP proxy requires authentication.

  • password [string] (optional)

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

¥Optional password to use if HTTP proxy requires authentication.

网络代理设置。

¥Network proxy settings.

  • slowMo [number] (optional)#

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

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

  • timeout [number] (optional)#

等待浏览器实例启动的最长时间(以毫秒为单位)。默认为 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.

  • tracesDir [string] (optional)#

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

¥If specified, traces are saved into this directory.

返回

¥Returns

  • [Promise]<[Browser]>#

launchPersistentContext

Added in: v1.8 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

  • userDataDir [string]#

用户数据目录的路径,该目录存储浏览器会话数据,例如 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.

  • options [Object] (optional)

    • acceptDownloads [boolean] (optional)#

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

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

  • args [Array]<[string]> (optional)#
warning

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.

  • baseURL [string] (optional)#

当使用 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

    • bypassCSP [boolean] (optional)#

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

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

  • channel [string] (optional)#

浏览器分发渠道。支持的值为 "chrome"、"chrome-beta"、"chrome-dev"、"chrome-canary"、"msedge"、"msedge-beta"、"msedge-dev"、"msedge-canary"。了解有关使用 谷歌浏览器和微软 Edge 的更多信息。

¥Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using Google Chrome and Microsoft Edge.

  • chromiumSandbox [boolean] (optional)#

启用 Chromium 沙箱。默认为 false

¥Enable Chromium sandboxing. Defaults to false.

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

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

¥Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. 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.

  • devtools [boolean] (optional)#
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.

  • downloadsPath [string] (optional)#

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

¥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.

  • env [Object]<[string], [string]|[number]|[boolean]> (optional)#

指定浏览器可见的环境变量。默认为 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.

  • extraHTTPHeaders [Object]<[string], [string]> (optional)#

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

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

  • firefoxUserPrefs [Object]<[string], [string]|[number]|[boolean]> (optional) Added in: v1.40#

火狐用户偏好。在 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'.

  • geolocation [Object] (optional)#

    • latitude [number]

纬度在 -90 到 90 之间。

¥Latitude between -90 and 90.

  • longitude [number]

经度在 -180 到 180 之间。

¥Longitude between -180 and 180.

  • accuracy [number] (optional)

非负精度值。默认为 0

¥Non-negative accuracy value. Defaults to 0.

  • handleSIGHUP [boolean] (optional)#

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

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

  • handleSIGINT [boolean] (optional)#

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

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

  • handleSIGTERM [boolean] (optional)#

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

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

  • hasTouch [boolean] (optional)#

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

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

  • headless [boolean] (optional)#

是否以无头模式运行浏览器。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.

  • httpCredentials [Object] (optional)#

    • username [string]

    • password [string]

    • origin [string] (optional)

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

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

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

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

  • ignoreDefaultArgs [boolean]|[Array]<[string]> (optional)#

如果是 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.

  • ignoreHTTPSErrors [boolean] (optional)#

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

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

  • isMobile [boolean] (optional)#

是否考虑 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.

  • javaScriptEnabled [boolean] (optional)#

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

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

  • locale [string] (optional)#

指定用户区域设置,例如 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.

  • logger [Logger] (optional)#

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

¥Logger sink for Playwright logging.

  • offline [boolean] (optional)#

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

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

  • permissions [Array]<[string]> (optional)#

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

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

  • proxy [Object] (optional)#

    • server [string]

用于所有请求的代理。支持 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.

  • bypass [string] (optional)

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

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

  • username [string] (optional)

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

¥Optional username to use if HTTP proxy requires authentication.

  • password [string] (optional)

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

¥Optional password to use if HTTP proxy requires authentication.

网络代理设置。

¥Network proxy settings.

  • recordHar [Object] (optional)#

    • omitContent [boolean] (optional)

用于控制是否省略 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.

    • path [string]

将 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.

    • urlFilter [string]|[RegExp] (optional)

用于过滤存储在 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.

  • recordVideo [Object] (optional)#

    • dir [string]

放置视频的目录路径。

¥Path to the directory to put videos into.

  • size [Object] (optional)

    • width [number]

视频帧宽度。

¥Video frame width.

  • height [number]

视频帧高度。

¥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'.

  • screen [Object] (optional)#

    • width [number]

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

¥page width in pixels.

  • height [number]

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

¥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.

    • slowMo [number] (optional)#

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

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

  • strictSelectors [boolean] (optional)#

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

  • timeout [number] (optional)#

等待浏览器实例启动的最长时间(以毫秒为单位)。默认为 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.

  • timezoneId [string] (optional)#

更改上下文的时区。有关支持的时区 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.

  • tracesDir [string] (optional)#

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

¥If specified, traces are saved into this directory.

  • userAgent [string] (optional)#

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

¥Specific user agent to use in this context.

  • videoSize [Object] (optional)#
Deprecated

Use recordVideo instead.

  • width [number]

视频帧宽度。

¥Video frame width.

  • height [number]

视频帧高度。

¥Video frame height.

  • videosPath [string] (optional)#
Deprecated

Use recordVideo instead.

  • viewport [null]|[Object] (optional)#

    • width [number]

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

¥page width in pixels.

  • height [number]

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

¥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.

note

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 in: v1.8browserType.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

warning

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.

  • channel [string] (optional)#

浏览器分发渠道。支持的值为 "chrome"、"chrome-beta"、"chrome-dev"、"chrome-canary"、"msedge"、"msedge-beta"、"msedge-dev"、"msedge-canary"。了解有关使用 谷歌浏览器和微软 Edge 的更多信息。

¥Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using Google Chrome and Microsoft Edge.

  • chromiumSandbox [boolean] (optional)#

启用 Chromium 沙箱。默认为 false

¥Enable Chromium sandboxing. Defaults to false.

  • devtools [boolean] (optional)#
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.

  • downloadsPath [string] (optional)#

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

¥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.

  • env [Object]<[string], [string]|[number]|[boolean]> (optional)#

指定浏览器可见的环境变量。默认为 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.

  • firefoxUserPrefs [Object]<[string], [string]|[number]|[boolean]> (optional)#

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

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

  • handleSIGHUP [boolean] (optional)#

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

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

  • handleSIGINT [boolean] (optional)#

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

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

  • handleSIGTERM [boolean] (optional)#

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

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

  • headless [boolean] (optional)#

是否以无头模式运行浏览器。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.

  • ignoreDefaultArgs [boolean]|[Array]<[string]> (optional)#

如果是 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.

  • logger [Logger] (optional)#

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

¥Logger sink for Playwright logging.

  • port [number] (optional)#

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

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

  • proxy [Object] (optional)#

    • server [string]

用于所有请求的代理。支持 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.

  • bypass [string] (optional)

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

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

  • username [string] (optional)

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

¥Optional username to use if HTTP proxy requires authentication.

  • password [string] (optional)

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

¥Optional password to use if HTTP proxy requires authentication.

网络代理设置。

¥Network proxy settings.

  • timeout [number] (optional)#

等待浏览器实例启动的最长时间(以毫秒为单位)。默认为 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.

  • tracesDir [string] (optional)#

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

¥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.

warning

wsPath can take control of the OS user. For this reason, you should use an unguessable token when using this option. :::任何了解以下内容的进程或网页(包括在 Playwright 中运行的进程或网页)

返回

¥Returns


name

Added in: v1.8browserType.name

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

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

用法

¥Usage

browserType.name();

返回

¥Returns