Skip to main content

BrowserContext

BrowserContexts 提供了一种操作多个独立浏览器会话的方法。

¥BrowserContexts provide a way to operate multiple independent browser sessions.

如果一个页面打开另一个页面,例如 通过 window.open 调用,弹出窗口将属于父页面的浏览器上下文。

¥If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page's browser context.

Playwright 允许使用 browser.new_context() 方法创建隔离的非持久性浏览器上下文。非持久性浏览器上下文不会将任何浏览数据写入磁盘。

¥Playwright allows creating isolated non-persistent browser contexts with browser.new_context() method. Non-persistent browser contexts don't write any browsing data to disk.

# create a new incognito browser context
context = browser.new_context()
# create a new page inside context.
page = context.new_page()
page.goto("https://example.com")
# dispose context once it is no longer needed.
context.close()

方法

¥Methods

add_cookies

Added before v1.9 browserContext.add_cookies

将 cookie 添加到此浏览器上下文中。此上下文中的所有页面都将安装这些 cookie。Cookie 可以通过 browser_context.cookies() 获取。

¥Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via browser_context.cookies().

用法

¥Usage

browser_context.add_cookies([cookie_object1, cookie_object2])

参数

¥Arguments

需要 url 或域/路径。可选的。

¥Either url or domain / path are required. Optional.

  • domain str (optional)

为了使 cookie 也适用于所有子域,请在域前添加一个点,如下所示:".example.com"。需要 url 或域/路径。可选的。

¥For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either url or domain / path are required. Optional.

  • path str (optional)

url 或域/路径是必需的(可选)。

¥Either url or domain / path are required Optional.

  • expires float (optional)

Unix 时间以秒为单位。可选的。

¥Unix time in seconds. Optional.

  • httpOnly bool (optional)

可选的。

¥Optional.

  • secure bool (optional)

可选的。

¥Optional.

  • sameSite "严格的" | "Lax" | "没有任何"(可选)

    ¥sameSite "Strict" | "Lax" | "None" (optional)

    可选的。

    ¥Optional.

返回

¥Returns


add_init_script

Added before v1.9 browserContext.add_init_script

添加将在以下场景之一进行评估的脚本:

¥Adds a script which would be evaluated in one of the following scenarios:

  • 每当在浏览器上下文中创建页面或导航页面时。

    ¥Whenever a page is created in the browser context or is navigated.

  • 每当在浏览器上下文中的任何页面中附加或导航子框架时。在这种情况下,脚本将在新附加的框架的上下文中进行评估。

    ¥Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.

该脚本在创建文档之后但在运行其任何脚本之前进行评估。这对于修改 JavaScript 环境很有用,例如 种子 Math.random

¥The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

用法

¥Usage

在页面加载之前覆盖 Math.random 的示例:

¥An example of overriding Math.random before the page loads:

// preload.js
Math.random = () => 42;
# in your playwright script, assuming the preload.js file is in same directory.
browser_context.add_init_script(path="preload.js")
注意

通过 browser_context.add_init_script()page.add_init_script() 安装的多个脚本的评估顺序未定义。

¥The order of evaluation of multiple scripts installed via browser_context.add_init_script() and page.add_init_script() is not defined.

参数

¥Arguments

JavaScript 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。可选的。

¥Path to the JavaScript file. If path is a relative path, then it is resolved relative to the current working directory. Optional.

  • script str (optional)#

要在浏览器上下文中的所有页面中评估的脚本。可选的。

¥Script to be evaluated in all pages in the browser context. Optional.

返回

¥Returns


clear_cookies

Added before v1.9 browserContext.clear_cookies

从上下文中删除 cookie。接受可选过滤器。

¥Removes cookies from context. Accepts optional filter.

用法

¥Usage

context.clear_cookies()
context.clear_cookies(name="session-id")
context.clear_cookies(domain="my-origin.com")
context.clear_cookies(path="/api/v1")
context.clear_cookies(name="session-id", domain="my-origin.com")

参数

¥Arguments

仅删除具有给定域的 cookie。

¥Only removes cookies with the given domain.

仅删除具有给定名称的 cookie。

¥Only removes cookies with the given name.

仅删除具有给定路径的 cookie。

¥Only removes cookies with the given path.

返回

¥Returns


clear_permissions

Added before v1.9 browserContext.clear_permissions

清除浏览器上下文的所有权限覆盖。

¥Clears all permission overrides for the browser context.

用法

¥Usage

context = browser.new_context()
context.grant_permissions(["clipboard-read"])
# do stuff ..
context.clear_permissions()

返回

¥Returns


close

Added before v1.9 browserContext.close

关闭浏览器上下文。属于浏览器上下文的所有页面都将被关闭。

¥Closes the browser context. All the pages that belong to the browser context will be closed.

注意

默认浏览器上下文无法关闭。

¥The default browser context cannot be closed.

用法

¥Usage

browser_context.close()
browser_context.close(**kwargs)

参数

¥Arguments

  • reason str (optional) Added in: v1.40#

被报告给因上下文关闭而中断的操作的原因。

¥The reason to be reported to the operations interrupted by the context closure.

返回

¥Returns


cookies

Added before v1.9 browserContext.cookies

如果未指定 URL,此方法将返回所有 cookie。如果指定了 URL,则仅返回影响这些 URL 的 cookie。

¥If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

用法

¥Usage

browser_context.cookies()
browser_context.cookies(**kwargs)

参数

¥Arguments

可选的 URL 列表。

¥Optional list of URLs.

返回

¥Returns

Unix 时间以秒为单位。

¥Unix time in seconds.

  • sameSite "严格的" | "Lax" | "没有任何"

    ¥sameSite "Strict" | "Lax" | "None"


expect_console_message

Added in: v1.34 browserContext.expect_console_message

执行操作并等待上下文中的页面中记录 ConsoleMessage。如果提供了谓词,它会将 ConsoleMessage 值传递给 predicate 函数,并等待 predicate(message) 返回真值。如果在 browser_context.on("console") 事件触发之前关闭页面,则会抛出错误。

¥Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the browser_context.on("console") event is fired.

用法

¥Usage

browser_context.expect_console_message()
browser_context.expect_console_message(**kwargs)

参数

¥Arguments

接收 ConsoleMessage 对象,并在等待应该解决时解析为真值。

¥Receives the ConsoleMessage object and resolves to truthy value when the waiting should resolve.

等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。可以使用 browser_context.set_default_timeout() 更改默认值。

¥Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the browser_context.set_default_timeout().

返回

¥Returns


expect_event

Added before v1.9 browserContext.expect_event

等待事件触发并将其值传递给谓词函数。当谓词返回真值时返回。如果上下文在事件触发之前关闭,则会抛出错误。返回事件数据值。

¥Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the context closes before the event is fired. Returns the event data value.

用法

¥Usage

with context.expect_event("page") as event_info:
page.get_by_role("button").click()
page = event_info.value

参数

¥Arguments

事件名称,相同的将传递到 browserContext.on(event)

¥Event name, same one would pass into browserContext.on(event).

接收事件数据并在等待解决时解析为真值。

¥Receives the event data and resolves to truthy value when the waiting should resolve.

等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。可以使用 browser_context.set_default_timeout() 更改默认值。

¥Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the browser_context.set_default_timeout().

返回

¥Returns


expect_page

Added in: v1.9 browserContext.expect_page

执行操作并等待上下文中创建新的 Page。如果提供了谓词,它会将 Page 值传递给 predicate 函数,并等待 predicate(event) 返回真值。如果在新的 Page 事件创建之前关闭上下文,则会抛出错误。

¥Performs action and waits for a new Page to be created in the context. If predicate is provided, it passes Page value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the context closes before new Page is created.

用法

¥Usage

browser_context.expect_page()
browser_context.expect_page(**kwargs)

参数

¥Arguments

接收 Page 对象,并在等待应该解决时解析为真值。

¥Receives the Page object and resolves to truthy value when the waiting should resolve.

等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。可以使用 browser_context.set_default_timeout() 更改默认值。

¥Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the browser_context.set_default_timeout().

返回

¥Returns


expose_binding

Added before v1.9 browserContext.expose_binding

该方法在上下文中每个页面的每个帧的 window 对象上添加一个名为 name 的函数。调用时,该函数执行 callback 并返回 Promise,该 Promise 解析为 callback 的返回值。如果 callback 返回 Promise,则将等待它。

¥The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.

callback 函数的第一个参数包含有关调用者的信息:{ browserContext: BrowserContext, page: Page, frame: Frame }

¥The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

有关仅页面版本,请参阅 page.expose_binding()

¥See page.expose_binding() for page-only version.

用法

¥Usage

将页面 URL 暴露给上下文中所有页面中的所有框架的示例:

¥An example of exposing page URL to all frames in all pages in the context:

from playwright.sync_api import sync_playwright, Playwright

def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch(headless=False)
context = browser.new_context()
context.expose_binding("pageURL", lambda source: source["page"].url)
page = context.new_page()
page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.get_by_role("button").click()

with sync_playwright() as playwright:
run(playwright)

参数

¥Arguments

窗口对象上的函数名称。

¥Name of the function on the window object.

将在 Playwright 上下文中调用的回调函数。

¥Callback function that will be called in the Playwright's context.

  • handle bool (optional)#
Deprecated

This option will be removed in the future.

是否将参数作为句柄传递,而不是按值传递。传递句柄时,仅支持一个参数。按值传递时,支持多个参数。

¥Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.

返回

¥Returns


expose_function

Added before v1.9 browserContext.expose_function

该方法在上下文中每个页面的每个帧的 window 对象上添加一个名为 name 的函数。调用时,该函数执行 callback 并返回 Promise,该 Promise 解析为 callback 的返回值。

¥The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

如果 callback 返回 Promise,则将等待它。

¥If the callback returns a Promise, it will be awaited.

有关仅页面版本,请参阅 page.expose_function()

¥See page.expose_function() for page-only version.

用法

¥Usage

向上下文中的所有页面添加 sha256 功能的示例:

¥An example of adding a sha256 function to all pages in the context:

import hashlib
from playwright.sync_api import sync_playwright

def sha256(text: str) -> str:
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()


def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch(headless=False)
context = browser.new_context()
context.expose_function("sha256", sha256)
page = context.new_page()
page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.get_by_role("button").click()

with sync_playwright() as playwright:
run(playwright)

参数

¥Arguments

窗口对象上的函数名称。

¥Name of the function on the window object.

将在 Playwright 上下文中调用的回调函数。

¥Callback function that will be called in the Playwright's context.

返回

¥Returns


grant_permissions

Added before v1.9 browserContext.grant_permissions

授予浏览器上下文指定的权限。如果指定,仅向给定源授予相应权限。

¥Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.

用法

¥Usage

browser_context.grant_permissions(permissions)
browser_context.grant_permissions(permissions, **kwargs)

参数

¥Arguments

要授予的权限列表。

¥A list of permissions to grant.

危险

支持的权限因浏览器而异,甚至同一浏览器的不同版本之间也不同。任何权限都可能在更新后停止工作。:::

¥Supported permissions differ between browsers, and even between different versions of the same browser. Any permission may stop working after an update.

以下是某些浏览器可能支持的一些权限:

¥Here are some permissions that may be supported by some browsers:

  • 'accelerometer'

  • 'ambient-light-sensor'

  • 'background-sync'

  • 'camera'

  • 'clipboard-read'

  • 'clipboard-write'

  • 'geolocation'

  • 'gyroscope'

  • 'magnetometer'

  • 'microphone'

  • 'midi-sysex'(系统独有的 MIDI)

    ¥'midi-sysex' (system-exclusive midi)

  • 'midi'

  • 'notifications'

  • 'payment-handler'

  • 'storage-access'

  • origin str (optional)#

授予权限的 origin,例如 “https://example.com”。

¥The origin to grant permissions to, e.g. "https://example.com".

返回

¥Returns


new_cdp_session

Added in: v1.11 browserContext.new_cdp_session
注意

CDP 会话仅在基于 Chromium 的浏览器上受支持。

¥CDP sessions are only supported on Chromium-based browsers.

返回新创建的会话。

¥Returns the newly created session.

用法

¥Usage

browser_context.new_cdp_session(page)

参数

¥Arguments

要为其创建新会话的目标。为了向后兼容,该参数被命名为 page,但它可以是 PageFrame 类型。

¥Target to create new session for. For backwards-compatibility, this parameter is named page, but it can be a Page or Frame type.

返回

¥Returns


new_page

Added before v1.9 browserContext.new_page

在浏览器上下文中创建一个新页面。

¥Creates a new page in the browser context.

用法

¥Usage

browser_context.new_page()

返回

¥Returns


route

Added before v1.9 browserContext.route

路由提供了修改浏览器上下文中任何页面触发的网络请求的功能。一旦启用路由,每个与 url 模式匹配的请求都将停止,除非它继续、完成或中止。

¥Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

注意

browser_context.route() 不会拦截 Service Worker 拦截的请求。参见 this 期。我们建议在使用请求拦截时通过将 service_workers 设置为 'block' 来禁用 Service Worker。

¥browser_context.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting service_workers to 'block'.

用法

¥Usage

中止所有图片请求的简单处理程序的示例:

¥An example of a naive handler that aborts all image requests:

context = browser.new_context()
page = context.new_page()
context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
page.goto("https://example.com")
browser.close()

或使用正则表达式模式的相同片段:

¥or the same snippet using a regex pattern instead:

context = browser.new_context()
page = context.new_page()
context.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
page = await context.new_page()
page = context.new_page()
page.goto("https://example.com")
browser.close()

可以检查请求来决定路由操作。例如,模拟包含某些发布数据的所有请求,并保留所有其他请求不变:

¥It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

def handle_route(route: Route):
if ("my-string" in route.request.post_data):
route.fulfill(body="mocked-data")
else:
route.continue_()
context.route("/api/**", handle_route)

当请求与两个处理程序匹配时,页面路由(使用 page.route() 设置)优先于浏览器上下文路由。

¥Page routes (set up with page.route()) take precedence over browser context routes when request matches both handlers.

要删除路由及其处理程序,你可以使用 browser_context.unroute()

¥To remove a route with its handler you can use browser_context.unroute().

注意

启用路由会禁用 http 缓存。

¥Enabling routing disables http cache.

参数

¥Arguments

在路由期间接收 URL 进行匹配的通配符模式、正则表达式模式或谓词。如果在上下文选项中设置了 base_url,并且提供的 URL 是不以 * 开头的字符串,则使用 new URL() 构造函数进行解析。

¥A glob pattern, regex pattern, or predicate that receives a URL to match during routing. If base_url is set in the context options and the provided URL is a string that does not start with *, it is resolved using the new URL() constructor.

处理程序函数来路由请求。

¥handler function to route the request.

  • times int (optional) Added in: v1.15#

路由应该多久使用一次。默认情况下每次都会使用它。

¥How often a route should be used. By default it will be used every time.

返回

¥Returns


route_from_har

Added in: v1.23 browserContext.route_from_har

如果指定,上下文中触发的网络请求将从 HAR 文件提供服务。了解有关 从 HAR 重播 的更多信息。

¥If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR.

Playwright 不会处理 Service Worker 从 HAR 文件中拦截的请求。参见 this 期。我们建议在使用请求拦截时通过将 service_workers 设置为 'block' 来禁用 Service Worker。

¥Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting service_workers to 'block'.

用法

¥Usage

browser_context.route_from_har(har)
browser_context.route_from_har(har, **kwargs)

参数

¥Arguments

带有预先记录的网络数据的 HAR 文件的路径。如果 path 是相对路径,则相对于当前工作目录进行解析。

¥Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.

  • not_found "abort" | "fallback"(可选)#

    ¥not_found "abort" | "fallback" (optional)#

    • 如果设置为 'abort',在 HAR 文件中找不到的任何请求都将被中止。

      ¥If set to 'abort' any request not found in the HAR file will be aborted.

    • 如果设置为 'fallback',则会进入处理程序链中的下一个路由处理程序。

      ¥If set to 'fallback' falls through to the next route handler in the handler chain. 默认为中止。

    ¥Defaults to abort.

  • update bool (optional)#

如果指定,则使用实际网络信息更新给定的 HAR,而不是从文件提供服务。当调用 browser_context.close() 时,文件被写入磁盘。

¥If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when browser_context.close() is called.

  • update_content "embed" | "attach"(可选)Added in: v1.32#

    ¥update_content "embed" | "attach" (optional) Added in: v1.32#

    用于控制资源内容管理的可选设置。如果指定了 attach,资源将作为单独的文件或条目保留在 ZIP 存档中。如果指定了 embed,内容将内联存储在 HAR 文件中。

    ¥Optional setting to control resource content management. 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.

  • update_mode "full" | "minimal"(可选)Added in: v1.32#

    ¥update_mode "full" | "minimal" (optional) Added in: v1.32#

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

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

用于匹配请求 URL 的通配符模式、正则表达式或谓词。HAR 文件只会提供 URL 与模式匹配的请求。如果未指定,则所有请求均由 HAR 文件提供服务。

¥A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.

返回

¥Returns


route_web_socket

Added in: v1.48 browserContext.route_web_socket

此方法允许修改浏览器上下文中任何页面建立的 websocket 连接。

¥This method allows to modify websocket connections that are made by any page in the browser context.

请注意,只有在调用此方法后创建的 WebSocket 才会被路由。建议在创建任何页面之前调用此方法。

¥Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before creating any pages.

用法

¥Usage

下面是一个简单的处理程序的示例,它会阻止一些 websocket 消息。有关更多详细信息和示例,请参阅 WebSocketRoute

¥Below is an example of a simple handler that blocks some websocket messages. See WebSocketRoute for more details and examples.

def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
if message == "to-be-blocked":
return
ws.send(message)

def handler(ws: WebSocketRoute):
ws.route_send(lambda message: message_handler(ws, message))
ws.connect()

context.route_web_socket("/ws", handler)

参数

¥Arguments

只有 URL 与此模式匹配的 WebSocket 才会被路由。字符串模式可以与 base_url 上下文选项相关。

¥Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the base_url context option.

路由 WebSocket 的处理程序函数。

¥Handler function to route the WebSocket.

返回

¥Returns


set_default_navigation_timeout

Added before v1.9 browserContext.set_default_navigation_timeout

此设置将更改以下方法和相关快捷方式的默认最大导航时间:

¥This setting will change the default maximum navigation time for the following methods and related shortcuts:

用法

¥Usage

browser_context.set_default_navigation_timeout(timeout)

参数

¥Arguments

最大导航时间(以毫秒为单位)

¥Maximum navigation time in milliseconds


set_default_timeout

Added before v1.9 browserContext.set_default_timeout

此设置将更改所有接受 timeout 选项的方法的默认最大时间。

¥This setting will change the default maximum time for all the methods accepting timeout option.

用法

¥Usage

browser_context.set_default_timeout(timeout)

参数

¥Arguments

最长时间(以毫秒为单位)。通过 0 禁用超时。

¥Maximum time in milliseconds. Pass 0 to disable timeout.


set_extra_http_headers

Added before v1.9 browserContext.set_extra_http_headers

额外的 HTTP 标头将随上下文中任何页面发起的每个请求一起发送。这些标头与使用 page.set_extra_http_headers() 设置的特定于页面的额外 HTTP 标头合并。如果页面覆盖特定标头,则将使用特定于页面的标头值而不是浏览器上下文标头值。

¥The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with page.set_extra_http_headers(). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

注意

browser_context.set_extra_http_headers() 不保证传出请求中标头的顺序。

¥browser_context.set_extra_http_headers() does not guarantee the order of headers in the outgoing requests.

用法

¥Usage

browser_context.set_extra_http_headers(headers)

参数

¥Arguments

包含随每个请求发送的附加 HTTP 标头的对象。所有标头值都必须是字符串。

¥An object containing additional HTTP headers to be sent with every request. All header values must be strings.

返回

¥Returns


set_geolocation

Added before v1.9 browserContext.set_geolocation

设置上下文的地理位置。通过 nullundefined 模拟位置不可用。

¥Sets the context's geolocation. Passing null or undefined emulates position unavailable.

用法

¥Usage

browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667})
注意

考虑使用 browser_context.grant_permissions() 授予浏览器上下文页面读取其地理位置的权限。

¥Consider using browser_context.grant_permissions() to grant permissions for the browser context pages to read its geolocation.

参数

¥Arguments

纬度在 -90 到 90 之间。

¥Latitude between -90 and 90.

经度在 -180 到 180 之间。

¥Longitude between -180 and 180.

  • accuracy float (optional)

非负精度值。默认为 0

¥Non-negative accuracy value. Defaults to 0.

返回

¥Returns


set_offline

Added before v1.9 browserContext.set_offline

用法

¥Usage

browser_context.set_offline(offline)

参数

¥Arguments

是否为浏览器上下文模拟网络离线。

¥Whether to emulate network being offline for the browser context.

返回

¥Returns


storage_state

Added before v1.9 browserContext.storage_state

返回此浏览器上下文的存储状态,包含当前 cookie、本地存储快照和 IndexedDB 快照。

¥Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.

用法

¥Usage

browser_context.storage_state()
browser_context.storage_state(**kwargs)

参数

¥Arguments

  • indexed_db bool (optional) Added in: v1.51#

设置为 true 以将 IndexedDB 包含在存储状态快照中。如果你的应用使用 IndexedDB 存储身份验证令牌(如 Firebase 身份验证),请启用此功能。

¥Set to true to include IndexedDB in the storage state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this.

保存存储状态的文件路径。如果 path 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,仍会返回存储状态,但不会保存到磁盘。

¥The file path to save the storage state to. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.

返回

¥Returns

Unix 时间以秒为单位。

¥Unix time in seconds.

  • sameSite "严格的" | "Lax" | "没有任何"

    ¥sameSite "Strict" | "Lax" | "None"


unroute

Added before v1.9 browserContext.unroute

删除使用 browser_context.route() 创建的路由。当不指定 handler 时,删除 url 的所有路由。

¥Removes a route created with browser_context.route(). When handler is not specified, removes all routes for the url.

用法

¥Usage

browser_context.unroute(url)
browser_context.unroute(url, **kwargs)

参数

¥Arguments

接收 URL 的通配符模式、正则表达式模式或谓词,用于向 browser_context.route() 注册路由。

¥A glob pattern, regex pattern or predicate receiving URL used to register a routing with browser_context.route().

用于向 browser_context.route() 注册路由的可选处理程序函数。

¥Optional handler function used to register a routing with browser_context.route().

返回

¥Returns


unroute_all

Added in: v1.41 browserContext.unroute_all

删除使用 browser_context.route()browser_context.route_from_har() 创建的所有路由。

¥Removes all routes created with browser_context.route() and browser_context.route_from_har().

用法

¥Usage

browser_context.unroute_all()
browser_context.unroute_all(**kwargs)

参数

¥Arguments

  • behavior "wait" | "ignoreErrors" | "default"(可选)#

    ¥behavior "wait" | "ignoreErrors" | "default" (optional)#

    指定是否等待已经运行的处理程序以及如果它们抛出错误该怎么办:

    ¥Specifies whether to wait for already running handlers and what to do if they throw errors:

    • 'default' - 不要等待当前处理程序调用(如果有)完成,如果未路由的处理程序抛出,可能会导致未处理的错误

      ¥'default' - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may result in unhandled error

    • 'wait' - 等待当前处理程序调用(如果有)完成

      ¥'wait' - wait for current handler calls (if any) to finish

    • 'ignoreErrors' - 不等待当前处理程序调用(如果有)完成,取消路由后处理程序抛出的所有错误都会被静默捕获

      ¥'ignoreErrors' - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught

返回

¥Returns


wait_for_event

Added before v1.9 browserContext.wait_for_event
注意

在大多数情况下,你应该使用 browser_context.expect_event()

¥In most cases, you should use browser_context.expect_event().

等待给定的 event 触发。如果提供了谓词,它会将事件的值传递给 predicate 函数,并等待 predicate(event) 返回真值。如果在触发 event 之前关闭浏览器上下文,则会抛出错误。

¥Waits for given event to fire. If predicate is provided, it passes event's value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the browser context is closed before the event is fired.

用法

¥Usage

browser_context.wait_for_event(event)
browser_context.wait_for_event(event, **kwargs)

参数

¥Arguments

事件名称,通常传递到 *.on(event) 中。

¥Event name, same one typically passed into *.on(event).

接收事件数据并在等待解决时解析为真值。

¥Receives the event data and resolves to truthy value when the waiting should resolve.

等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。可以使用 browser_context.set_default_timeout() 更改默认值。

¥Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the browser_context.set_default_timeout().

返回

¥Returns


属性

¥Properties

background_pages

Added in: v1.11 browserContext.background_pages
注意

仅基于 Chromium 的浏览器支持后台页面。

¥Background pages are only supported on Chromium-based browsers.

上下文中所有现有的背景页面。

¥All existing background pages in the context.

用法

¥Usage

browser_context.background_pages

返回

¥Returns


browser

Added before v1.9 browserContext.browser

返回上下文的浏览器实例。如果它作为持久上下文启动,则返回 null。

¥Returns the browser instance of the context. If it was launched as a persistent context null gets returned.

用法

¥Usage

browser_context.browser

返回

¥Returns


clock

Added in: v1.45 browserContext.clock

Playwright 能够模拟时钟和时间的流逝。

¥Playwright has ability to mock clock and passage of time.

用法

¥Usage

browser_context.clock

类型

¥Type


pages

Added before v1.9 browserContext.pages

返回上下文中所有打开的页面。

¥Returns all open pages in the context.

用法

¥Usage

browser_context.pages

返回

¥Returns


request

Added in: v1.16 browserContext.request

与此上下文关联的 API 测试助手。使用此 API 触发的请求将使用上下文 cookie。

¥API testing helper associated with this context. Requests made with this API will use context cookies.

用法

¥Usage

browser_context.request

类型

¥Type


service_workers

Added in: v1.11 browserContext.service_workers
注意

Service Worker 仅在基于 Chromium 的浏览器上受支持。

¥Service workers are only supported on Chromium-based browsers.

上下文中所有现有的 Service Worker。

¥All existing service workers in the context.

用法

¥Usage

browser_context.service_workers

返回

¥Returns


tracing

Added in: v1.12 browserContext.tracing

用法

¥Usage

browser_context.tracing

类型

¥Type


事件

¥Events

on("backgroundpage")

Added in: v1.11 browserContext.on("backgroundpage")
注意

仅适用于 Chromium 浏览器的持久上下文。

¥Only works with Chromium browser's persistent context.

在上下文中创建新的背景页面时触发。

¥Emitted when new background page is created in the context.

background_page = context.wait_for_event("backgroundpage")

用法

¥Usage

browser_context.on("backgroundpage", handler)

事件数据

¥Event data


on("close")

Added before v1.9 browserContext.on("close")

当浏览器上下文关闭时触发。发生这种情况可能是由于以下原因之一:

¥Emitted when Browser context gets closed. This might happen because of one of the following:

  • 浏览器上下文已关闭。

    ¥Browser context is closed.

  • 浏览器应用已关闭或崩溃。

    ¥Browser application is closed or crashed.

  • 调用了 browser.close() 方法。

    ¥The browser.close() method was called.

用法

¥Usage

browser_context.on("close", handler)

事件数据

¥Event data


on("console")

Added in: v1.34 browserContext.on("console")

当页面内的 JavaScript 调用控制台 API 方法之一时触发,例如 console.logconsole.dir

¥Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir.

传递到 console.log 和页面的参数可在 ConsoleMessage 事件处理程序参数上使用。

¥The arguments passed into console.log and the page are available on the ConsoleMessage event handler argument.

用法

¥Usage

def print_args(msg):
for arg in msg.args:
print(arg.json_value())

context.on("console", print_args)
page.evaluate("console.log('hello', 5, { foo: 'bar' })")

事件数据

¥Event data


on("dialog")

Added in: v1.34 browserContext.on("dialog")

当 JavaScript 对话框出现时触发,例如 alertpromptconfirmbeforeunload。监听者必须选择 dialog.accept()dialog.dismiss() 对话 - 否则页面将 freeze 等待对话框,并且单击等操作将永远不会完成。

¥Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener must either dialog.accept() or dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

用法

¥Usage

context.on("dialog", lambda dialog: dialog.accept())
注意

当没有 page.on("dialog")browser_context.on("dialog") 监听器存在时,所有对话框都会自动关闭。

¥When no page.on("dialog") or browser_context.on("dialog") listeners are present, all dialogs are automatically dismissed.

事件数据

¥Event data


on("page")

Added before v1.9 browserContext.on("page")

当在 BrowserContext 中创建新页面时会触发该事件。该页面可能仍在加载。该事件还将针对弹出页面触发。另请参阅 page.on("popup") 以接收有关与特定页面相关的弹出窗口的事件。

¥The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also page.on("popup") to receive events about popups relevant to a specific page.

该页面最早可用的时刻是导航到初始 URL 时。例如,当使用 window.open('http://example.com') 打开弹出窗口时,当对“http://example.com”的网络请求完成并且其响应已开始在弹出窗口中加载时,将触发此事件。如果你想路由/监听此网络请求,请分别使用 browser_context.route()browser_context.on("request"),而不是 Page 上的类似方法。

¥The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to this network request, use browser_context.route() and browser_context.on("request") respectively instead of similar methods on the Page.

with context.expect_page() as page_info:
page.get_by_text("open new page").click(),
page = page_info.value
print(page.evaluate("location.href"))
注意

使用 page.wait_for_load_state() 等待页面进入特定状态(在大多数情况下你不需要它)。

¥Use page.wait_for_load_state() to wait until the page gets to a particular state (you should not need it in most cases).

用法

¥Usage

browser_context.on("page", handler)

事件数据

¥Event data


on("request")

Added in: v1.12 browserContext.on("request")

当从通过此上下文创建的任何页面触发请求时触发。request 对象是只读的。要仅监听来自特定页面的请求,请使用 page.on("request")

¥Emitted when a request is issued from any pages created through this context. The request object is read-only. To only listen for requests from a particular page, use page.on("request").

为了拦截和改变请求,请参阅 browser_context.route()page.route()

¥In order to intercept and mutate requests, see browser_context.route() or page.route().

用法

¥Usage

browser_context.on("request", handler)

事件数据

¥Event data


on("requestfailed")

Added in: v1.12 browserContext.on("requestfailed")

当请求失败时触发,例如超时。要仅监听来自特定页面的失败请求,请使用 page.on("requestfailed")

¥Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use page.on("requestfailed").

注意

从 HTTP 角度来看,HTTP 错误响应(例如 404 或 503)仍然是成功响应,因此请求将通过 browser_context.on("requestfinished") 事件完成,而不是通过 browser_context.on("requestfailed") 事件完成。

¥HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with browser_context.on("requestfinished") event and not with browser_context.on("requestfailed").

用法

¥Usage

browser_context.on("requestfailed", handler)

事件数据

¥Event data


on("requestfinished")

Added in: v1.12 browserContext.on("requestfinished")

下载响应正文后请求成功完成时触发。对于成功响应,事件顺序为 requestresponserequestfinished。要监听来自特定页面的成功请求,请使用 page.on("requestfinished")

¥Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished. To listen for successful requests from a particular page, use page.on("requestfinished").

用法

¥Usage

browser_context.on("requestfinished", handler)

事件数据

¥Event data


on("response")

Added in: v1.12 browserContext.on("response")

当收到请求的 response 状态和标头时触发。对于成功响应,事件顺序为 requestresponserequestfinished。要监听来自特定页面的响应事件,请使用 page.on("response")

¥Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished. To listen for response events from a particular page, use page.on("response").

用法

¥Usage

browser_context.on("response", handler)

事件数据

¥Event data


on("serviceworker")

Added in: v1.11 browserContext.on("serviceworker")
注意

Service Worker 仅在基于 Chromium 的浏览器上受支持。

¥Service workers are only supported on Chromium-based browsers.

在上下文中创建新的 Service Worker 时触发。

¥Emitted when new service worker is created in the context.

用法

¥Usage

browser_context.on("serviceworker", handler)

事件数据

¥Event data


on("weberror")

Added in: v1.38 browserContext.on("weberror")

当此上下文中的任何页面中的异常未处理时触发。要监听特定页面的错误,请改用 page.on("pageerror")

¥Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, use page.on("pageerror") instead.

用法

¥Usage

browser_context.on("weberror", handler)

事件数据

¥Event data