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:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
chromium = playwright.chromium
browser = chromium.launch()
page = browser.new_page()
page.goto("https://example.com")
# other actions...
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
chromium = playwright.chromium
browser = await chromium.launch()
page = await browser.new_page()
await page.goto("https://example.com")
# other actions...
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
方法
¥Methods
connect
Added before v1.9此方法将 Playwright 附加到通过 Node.js 中的 BrowserType.launchServer
创建的现有浏览器实例。
¥This method attaches Playwright to an existing browser instance created via BrowserType.launchServer
in Node.js.
连接的 Playwright 实例的主要和次要版本需要与启动浏览器的 Playwright 版本相匹配(1.2.3 → 与 1.2.x 兼容)。
¥The major and minor version of the Playwright instance that connects needs to match the version of Playwright that launches the browser (1.2.3 → is compatible with 1.2.x).
用法
¥Usage
browser_type.connect(ws_endpoint)
browser_type.connect(ws_endpoint, **kwargs)
参数
¥Arguments
要连接到的 Playwright 浏览器 websocket 端点。你可以通过 BrowserServer.wsEndpoint
获取此端点。
¥A Playwright browser websocket endpoint to connect to. You obtain this endpoint via BrowserServer.wsEndpoint
.
此选项将连接客户端上可用的网络公开给正在连接的浏览器。由逗号分隔的规则列表组成。
¥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:
-
主机名模式,例如:
example.com
、*.org:99
、x.*.y.com
、*foo.org
。¥Hostname pattern, for example:
example.com
,*.org:99
,x.*.y.com
,*foo.org
. -
IP 字面量,例如:
127.0.0.1
、0.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
. -
匹配本地环回接口的
<loopback>
:localhost
、*.localhost
、127.0.0.1
、[::1]
。¥
<loopback>
that matches local loopback interfaces:localhost
,*.localhost
,127.0.0.1
,[::1]
.
一些常见的例子:
¥Some common examples:
-
"*"
暴露所有网络。¥
"*"
to expose all network. -
"<loopback>"
暴露本地主机网络。¥
"<loopback>"
to expose localhost network. -
"*.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.
将 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.
等待建立连接的最长时间(以毫秒为单位)。默认为 0
(无超时)。
¥Maximum time in milliseconds to wait for the connection to be established. Defaults to 0
(no timeout).
返回
¥Returns
connect_over_cdp
Added in: v1.9此方法使用 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.
此连接比通过 browser_type.connect() 的 Playwright 协议连接保真度低得多。如果你遇到问题或尝试使用高级功能,你可能需要使用 browser_type.connect()。
¥This connection is significantly lower fidelity than the Playwright protocol connection via browser_type.connect(). If you are experiencing issues or attempting to use advanced functionality, you probably want to use browser_type.connect().
用法
¥Usage
- Sync
- Async
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
default_context = browser.contexts[0]
page = default_context.pages[0]
browser = await playwright.chromium.connect_over_cdp("http://localhost:9222")
default_context = browser.contexts[0]
page = default_context.pages[0]
参数
¥Arguments
要连接的 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
.
与连接请求一起发送的附加 HTTP 标头。可选的。
¥Additional HTTP headers to be sent with connect request. Optional.
将 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.
等待建立连接的最长时间(以毫秒为单位)。默认为 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
launch
Added before v1.9返回浏览器实例。
¥Returns the browser instance.
用法
¥Usage
你可以使用 ignore_default_args 从默认参数中过滤掉 --mute-audio
:
¥You can use ignore_default_args to filter out --mute-audio
from default arguments:
- Sync
- Async
browser = playwright.chromium.launch( # or "firefox" or "webkit".
ignore_default_args=["--mute-audio"]
)
browser = await playwright.chromium.launch( # or "firefox" or "webkit".
ignore_default_args=["--mute-audio"]
)
仅限 Chromium 的 Playwright 还可用于控制 Google Chrome 或 Microsoft Edge 浏览器,但它与打包的 Chromium 版本配合使用效果最佳。不保证它可以与任何其他版本一起使用。使用 executable_path 选项时要格外小心。
¥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 executable_path 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
.
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
.
downloads_path
Union[str, pathlib.Path] (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.
指定浏览器可见的环境变量。默认为 process.env
。
¥Specify environment variables that will be visible to the browser. Defaults to process.env
.
executable_path
Union[str, pathlib.Path] (optional)#
要运行的浏览器可执行文件(而不是打包的可执行文件)的路径。如果 executable_path 是相对路径,则相对于当前工作目录进行解析。请注意,Playwright 仅适用于打包的 Chromium、Firefox 或 WebKit,使用风险由你自行承担。
¥Path to a browser executable to run instead of the bundled one. If executable_path 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
.
用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128
或 socks5://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
str (optional)
用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"
。
¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com"
.
username
str (optional)
如果 HTTP 代理需要身份验证,则使用可选的用户名。
¥Optional username to use if HTTP proxy requires authentication.
password
str (optional)
如果 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.
traces_dir
Union[str, pathlib.Path] (optional)#
如果指定,跟踪将保存到此目录中。
¥If specified, traces are saved into this directory.
返回
¥Returns
launch_persistent_context
Added before v1.9返回持久浏览器上下文实例。
¥Returns the persistent browser context instance.
启动使用位于 user_data_dir 的持久存储的浏览器并返回唯一的上下文。关闭此上下文将自动关闭浏览器。
¥Launches browser that uses persistent storage located at user_data_dir and returns the only context. Closing this context will automatically close the browser.
用法
¥Usage
browser_type.launch_persistent_context(user_data_dir)
browser_type.launch_persistent_context(user_data_dir, **kwargs)
参数
¥Arguments
user_data_dir
Union[str, pathlib.Path]#
用户数据目录的路径,该目录存储浏览器会话数据,例如 cookie 和本地存储。传递一个空字符串以创建临时目录。
¥Path to a User Data Directory, which stores browser session data like cookies and local storage. Pass an empty string to create a temporary directory.
Chromium 和 火狐浏览器 的更多详细信息。Chromium 的用户数据目录是 chrome://version
中 "轮廓路径" 的父目录。
¥More details for Chromium and Firefox. Chromium's user data directory is the parent directory of the "Profile Path" seen at chrome://version
.
请注意,浏览器不允许使用同一个用户数据目录启动多个实例。
¥Note that browsers do not allow launching multiple instances with the same User Data Directory.
是否自动下载所有附件。默认为 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.wait_for_url()、page.expect_request() 或 page.expect_response() 时,它会使用 URL()
构造函数来构建相应的 URL,从而考虑基本 URL。默认情况下取消设置。示例:
¥When using page.goto(), page.route(), page.wait_for_url(), page.expect_request(), or page.expect_response() 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 inhttp://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 inhttp://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 inhttp://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.
certPath
Union[str, pathlib.Path] (optional)
PEM 格式的证书文件路径。
¥Path to the file with the certificate in PEM format.
cert
bytes (optional)
PEM 格式的证书的直接值。
¥Direct value of the certificate in PEM format.
keyPath
Union[str, pathlib.Path] (optional)
PEM 格式的私钥文件路径。
¥Path to the file with the private key in PEM format.
key
bytes (optional)
PEM 格式的私钥的直接值。
¥Direct value of the private key in PEM format.
pfxPath
Union[str, pathlib.Path] (optional)
PFX 或 PKCS12 编码的私钥和证书链的路径。
¥Path to the PFX or PKCS12 encoded private key and certificate chain.
pfx
bytes (optional)
PFX 或 PKCS12 编码的私钥和证书链的直接值。
¥Direct value of the PFX or PKCS12 encoded private key and certificate chain.
passphrase
str (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
要使用的客户端证书数组。每个证书对象必须同时具有 certPath
和 keyPath
、单个 pfxPath
或它们对应的直接值等价物(cert
和 key
或 pfx
)。如果证书已加密,则可选地提供 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
.
-
color_scheme
"light" | "dark" | "no-preference" | "null"(可选)#¥
color_scheme
"light" | "dark" | "no-preference" | "null" (optional)#模拟 prefers-colors-scheme 媒体功能,支持的值为
'light'
和'dark'
。详细信息请参见 page.emulate_media()。传递'null'
会将模拟重置为系统默认值。默认为'light'
。¥Emulates prefers-colors-scheme media feature, supported values are
'light'
and'dark'
. See page.emulate_media() for more details. Passing'null'
resets emulation to system defaults. Defaults to'light'
. -
contrast
"no-preference" | "more" | "null"(可选)#¥
contrast
"no-preference" | "more" | "null" (optional)#模拟
'prefers-contrast'
媒体功能,支持的值为'no-preference'
、'more'
。详细信息请参见 page.emulate_media()。传递'null'
会将模拟重置为系统默认值。默认为'no-preference'
。¥Emulates
'prefers-contrast'
media feature, supported values are'no-preference'
,'more'
. See page.emulate_media() for more details. Passing'null'
resets emulation to system defaults. Defaults to'no-preference'
.
指定设备比例因子(可以视为 dpr)。默认为 1
。了解有关 使用设备比例因子模拟设备 的更多信息。
¥Specify device scale factor (can be thought of as dpr). Defaults to 1
. Learn more about emulating devices with device scale factor.
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
.
downloads_path
Union[str, pathlib.Path] (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.
指定浏览器可见的环境变量。默认为 process.env
。
¥Specify environment variables that will be visible to the browser. Defaults to process.env
.
executable_path
Union[str, pathlib.Path] (optional)#
要运行的浏览器可执行文件(而不是打包的可执行文件)的路径。如果 executable_path 是相对路径,则相对于当前工作目录进行解析。请注意,Playwright 仅适用于打包的 Chromium、Firefox 或 WebKit,使用风险由你自行承担。
¥Path to a browser executable to run instead of the bundled one. If executable_path 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
.
-
forced_colors
"active" | "none" | "null"(可选)#¥
forced_colors
"active" | "none" | "null" (optional)#模拟
'forced-colors'
媒体功能,支持的值为'active'
、'none'
。详细信息请参见 page.emulate_media()。传递'null'
会将模拟重置为系统默认值。默认为'none'
。¥Emulates
'forced-colors'
media feature, supported values are'active'
,'none'
. See page.emulate_media() for more details. Passing'null'
resets emulation to system defaults. Defaults to'none'
.
纬度在 -90 到 90 之间。
¥Latitude between -90 and 90.
longitude
float
经度在 -180 到 180 之间。
¥Longitude between -180 and 180.
accuracy
float (optional)
非负精度值。默认为 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 withWWW-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-GB
、de-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.
不强制固定视口,允许在头显模式下调整窗口大小。
¥Does not enforce fixed viewport, allows resizing window in the headed mode.
是否模拟网络离线。默认为 false
。了解有关 网络模拟 的更多信息。
¥Whether to emulate network being offline. Defaults to false
. Learn more about network emulation.
授予此上下文中所有页面的权限列表。详细信息请参见 browser_context.grant_permissions()。默认为无。
¥A list of permissions to grant to all pages in this context. See browser_context.grant_permissions() for more details. Defaults to none.
用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128
或 socks5://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
str (optional)
用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"
。
¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com"
.
username
str (optional)
如果 HTTP 代理需要身份验证,则使用可选的用户名。
¥Optional username to use if HTTP proxy requires authentication.
password
str (optional)
如果 HTTP 代理需要身份验证,则使用可选密码。
¥Optional password to use if HTTP proxy requires authentication.
网络代理设置。
¥Network proxy settings.
-
record_har_content
"omit" | "embed" | "attach"(可选)#¥
record_har_content
"omit" | "embed" | "attach" (optional)#用于控制资源内容管理的可选设置。如果指定了
omit
,则不会保留内容。如果指定了attach
,则资源将作为单独的文件持久化,所有这些文件都将与 HAR 文件一起存档。默认为embed
,它根据 HAR 规范将内容内联存储在 HAR 文件中。¥Optional setting to control resource content management. If
omit
is specified, content is not persisted. Ifattach
is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. Defaults toembed
, which stores content inline the HAR file as per HAR specification. -
record_har_mode
"full" | "minimal"(可选)#¥
record_har_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 tofull
.
用于控制是否省略 HAR 中的请求内容的可选设置。默认为 false
。
¥Optional setting to control whether to omit request content from the HAR. Defaults to false
.
record_har_path
Union[str, pathlib.Path] (optional)#
启用 HAR 将所有页面录制到文件系统上指定的 HAR 文件中。如果未指定,则不会记录 HAR。确保调用 browser_context.close() 以保存 HAR 文件。
¥Enables HAR recording for all pages into the specified HAR file on the filesystem. If not specified, the HAR is not recorded. Make sure to call browser_context.close() for the HAR to be saved.
-
record_video_dir
Union[str, pathlib.Path] (optional)#
启用视频录制将所有页面录制到指定目录中。如果未指定,则不会录制视频。确保调用 browser_context.close() 以保存视频。
¥Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure to call browser_context.close() for videos to be saved.
视频帧宽度。
¥Video frame width.
height
int
视频帧高度。
¥Video frame height.
录制视频的尺寸。如果未指定,大小将等于 viewport
缩小以适合 800x800。如果未明确配置 viewport
,则视频大小默认为 800x450。如有必要,每页的实际图片将按比例缩小以适合指定的尺寸。
¥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.
-
reduced_motion
"reduce" | "no-preference" | "null"(可选)#¥
reduced_motion
"reduce" | "no-preference" | "null" (optional)#模拟
'prefers-reduced-motion'
媒体功能,支持的值为'reduce'
、'no-preference'
。详细信息请参见 page.emulate_media()。传递'null'
会将模拟重置为系统默认值。默认为'no-preference'
。¥Emulates
'prefers-reduced-motion'
media feature, supported values are'reduce'
,'no-preference'
. See page.emulate_media() for more details. Passing'null'
resets emulation to system defaults. Defaults to'no-preference'
.
页面宽度(以像素为单位)。
¥page width in pixels.
height
int
页面高度(以像素为单位)。
¥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.
-
service_workers
"allow" | "block"(可选)#¥
service_workers
"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.
traces_dir
Union[str, pathlib.Path] (optional)#
如果指定,跟踪将保存到此目录中。
¥If specified, traces are saved into this directory.
在此上下文中使用的特定用户代理。
¥Specific user agent to use in this context.
页面宽度(以像素为单位)。
¥page width in pixels.
height
int
页面高度(以像素为单位)。
¥page height in pixels.
为每个页面设置一致的视口。默认为 1280x720 视口。no_viewport
禁用固定视口。了解有关 视口模拟 的更多信息。
¥Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. no_viewport
disables the fixed viewport. Learn more about viewport emulation.
返回
¥Returns
属性
¥Properties
executable_path
Added before v1.9Playwright 希望找到打包的浏览器可执行文件的路径。
¥A path where Playwright expects to find a bundled browser executable.
用法
¥Usage
browser_type.executable_path
返回
¥Returns
name
Added before v1.9返回浏览器名称。例如:'chromium'
、'webkit'
或 'firefox'
。
¥Returns browser name. For example: 'chromium'
, 'webkit'
or 'firefox'
.
用法
¥Usage
browser_type.name
返回
¥Returns