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.
- Sync
- Async
# 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()
# create a new incognito browser context
context = await browser.new_context()
# create a new page inside context.
page = await context.new_page()
await page.goto("https://example.com")
# dispose context once it is no longer needed.
await context.close()
方法
🌐 Methods
add_cookies
Added before v1.9将 cookies 添加到此浏览器上下文中。此上下文中的所有页面都会安装这些 cookies。可以通过 browser_context.cookies() 获取 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().
用法
- Sync
- Async
browser_context.add_cookies([cookie_object1, cookie_object2])
await browser_context.add_cookies([cookie_object1, cookie_object2])
参数
cookiesList[Dict]#-
namestr -
valuestr -
urlstr (optional)需要
url或domain和path两者。可选。 -
domainstr (optional)为了让 cookie 也适用于所有子域,请在域名前加一个点,例如:“.example.com”。
url或者同时domain和path是必填项。可选。 -
pathstr (optional)需要
url或domain和path两者。可选。 -
expiresfloat (optional)Unix 时间(以秒为单位)。可选。
-
httpOnlybool (optional)可选的。
-
securebool (optional)可选的。
-
sameSite"Strict" | "Lax" | "None" (optional)可选的。
-
partitionKeystr (optional)对于分区的第三方 Cookie(也称为 CHIPS),分区键。可选。
-
返回
add_init_script
Added before v1.9添加将在以下场景之一进行评估的脚本:
🌐 Adds a script which would be evaluated in one of the following scenarios:
- 每当在浏览器上下文中创建页面或导航页面时。
- 每当浏览器上下文中的任意页面附加或导航子框架时,在这种情况下,脚本会在新附加的框架上下文中执行。
脚本在文档创建后但在其任何脚本运行之前进行评估。这对于修改 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.
用法
在页面加载之前重写 Math.random 的示例:
🌐 An example of overriding Math.random before the page loads:
// preload.js
Math.random = () => 42;
- Sync
- Async
# in your playwright script, assuming the preload.js file is in same directory.
browser_context.add_init_script(path="preload.js")
# in your playwright script, assuming the preload.js file is in same directory.
await 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.
参数
-
pathUnion[str, pathlib.Path] (optional)#JavaScript 文件的路径。如果
path是相对路径,则相对于当前工作目录解析。可选。 -
在浏览器上下文中对所有页面执行的脚本。可选。
返回
clear_cookies
Added before v1.9从上下文中移除 cookies。可接受可选过滤器。
🌐 Removes cookies from context. Accepts optional filter.
用法
- Sync
- Async
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")
await context.clear_cookies()
await context.clear_cookies(name="session-id")
await context.clear_cookies(domain="my-origin.com")
await context.clear_cookies(path="/api/v1")
await context.clear_cookies(name="session-id", domain="my-origin.com")
参数
-
domainstr | Pattern (optional) Added in: v1.43#仅删除具有给定域的 cookie。
-
namestr | Pattern (optional) Added in: v1.43#仅删除具有给定名称的 cookie。
-
pathstr | Pattern (optional) Added in: v1.43#仅删除具有给定路径的 cookie。
返回
clear_permissions
Added before v1.9清除浏览器上下文的所有权限覆盖。
🌐 Clears all permission overrides for the browser context.
用法
- Sync
- Async
context = browser.new_context()
context.grant_permissions(["clipboard-read"])
# do stuff ..
context.clear_permissions()
context = await browser.new_context()
await context.grant_permissions(["clipboard-read"])
# do stuff ..
context.clear_permissions()
返回
close
Added before v1.9关闭浏览器上下文。属于该浏览器上下文的所有页面将被关闭。
🌐 Closes the browser context. All the pages that belong to the browser context will be closed.
默认浏览器上下文无法关闭。
🌐 The default browser context cannot be closed.
用法
browser_context.close()
browser_context.close(**kwargs)
参数
返回
cookies
Added before v1.9如果未指定 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.
用法
browser_context.cookies()
browser_context.cookies(**kwargs)
参数
返回
expect_console_message
Added in: v1.34执行操作并等待上下文中的页面记录 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.
用法
browser_context.expect_console_message()
browser_context.expect_console_message(**kwargs)
参数
-
predicateCallable[ConsoleMessage]:bool (optional)#接收 ConsoleMessage 对象,并在等待应当解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_event
Added before v1.9等待事件触发并将其值传递给谓词函数。当谓词返回真值时返回。如果在事件触发前上下文关闭,将抛出错误。返回事件数据值。
🌐 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.
用法
- Sync
- Async
with context.expect_event("page") as event_info:
page.get_by_role("button").click()
page = event_info.value
async with context.expect_event("page") as event_info:
await page.get_by_role("button").click()
page = await event_info.value
参数
-
事件名称,相同的会传递到
browserContext.on(event)。 -
predicateCallable (optional)#接收事件数据并在等待解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_page
Added in: v1.9执行操作并等待在上下文中创建新的 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.
用法
browser_context.expect_page()
browser_context.expect_page(**kwargs)
参数
-
predicateCallable[Page]:bool (optional)#接收 Page 对象,并在等待条件应该满足时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expose_binding
Added before v1.9该方法在上下文中每个页面的每一帧的 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.
用法
将页面 URL 暴露给上下文中所有页面中的所有框架的示例:
🌐 An example of exposing page URL to all frames in all pages in the context:
- Sync
- Async
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)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch(headless=False)
context = await browser.new_context()
await context.expose_binding("pageURL", lambda source: source["page"].url)
page = await context.new_page()
await page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.get_by_role("button").click()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
参数
-
窗口对象上的函数名称。
-
将在 Playwright 上下文中调用的回调函数。
-
已弃用
此选项将在未来被移除。
是否将参数作为句柄传递,而不是按值传递。传递句柄时,只支持一个参数。按值传递时,支持多个参数。
返回
expose_function
Added before v1.9该方法在上下文中每个页面的每一帧的 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.
用法
在上下文中向所有页面添加 sha256 函数的示例:
🌐 An example of adding a sha256 function to all pages in the context:
- Sync
- Async
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)
import asyncio
import hashlib
from playwright.async_api import async_playwright, Playwright
def sha256(text: str) -> str:
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch(headless=False)
context = await browser.new_context()
await context.expose_function("sha256", sha256)
page = await context.new_page()
await page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.get_by_role("button").click()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
参数
返回
grant_permissions
Added before v1.9授予浏览器上下文指定的权限。仅在指定时向给定来源授予相应的权限。
🌐 Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
用法
browser_context.grant_permissions(permissions)
browser_context.grant_permissions(permissions, **kwargs)
参数
-
要授予的权限列表。
danger不同浏览器支持的权限各不相同,甚至同一浏览器的不同版本之间也有所差异。任何权限在更新后都可能停止工作。
以下是某些浏览器可能支持的一些权限:
'accelerometer''ambient-light-sensor''background-sync''camera''clipboard-read''clipboard-write''geolocation''gyroscope''local-fonts''local-network-access''magnetometer''microphone''midi-sysex'(系统专用MIDI)'midi''notifications''payment-handler''storage-access'
-
origin 用于授予权限,例如 "https://example.com"。
返回
new_cdp_session
Added in: v1.11CDP 会话仅支持基于 Chromium 的浏览器。
🌐 CDP sessions are only supported on Chromium-based browsers.
返回新创建的会话。
🌐 Returns the newly created session.
用法
browser_context.new_cdp_session(page)
参数
返回
new_page
Added before v1.9在浏览器上下文中创建一个新页面。
🌐 Creates a new page in the browser context.
用法
browser_context.new_page()
返回
route
Added before v1.9路由功能提供了修改浏览器上下文中任何页面发出的网络请求的能力。一旦启用路由,每个匹配 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 Worker,通过将 service_workers 设置为 'block'。:::
用法
中止所有图片请求的简单处理程序的示例:
🌐 An example of a naive handler that aborts all image requests:
- Sync
- Async
context = browser.new_context()
page = context.new_page()
context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
page.goto("https://example.com")
browser.close()
context = await browser.new_context()
page = await context.new_page()
await context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
await page.goto("https://example.com")
await browser.close()
或使用正则表达式模式的相同片段:
🌐 or the same snippet using a regex pattern instead:
- Sync
- Async
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()
context = await browser.new_context()
page = await context.new_page()
await context.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
page = await context.new_page()
await page.goto("https://example.com")
await browser.close()
可以检查请求以决定路由操作。例如,模拟所有包含某些 POST 数据的请求,而将所有其他请求保持原样:
🌐 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:
- Sync
- Async
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)
async def handle_route(route: Route):
if ("my-string" in route.request.post_data):
await route.fulfill(body="mocked-data")
else:
await route.continue_()
await 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.
参数
-
urlstr | Pattern | Callable[URL]:bool#一个通配符模式、正则表达式模式或谓词,用于在路由期间接收要匹配的 URL。如果在上下文选项中设置了 base_url,并且提供的 URL 是一个不以
*开头的字符串,则会使用new URL()构造函数进行解析。 -
handlerCallable[Route, Request]:Promise[Any] | Any#处理程序函数来路由请求。
-
timesint (optional) Added in: v1.15#一个路由应该使用的频率。默认情况下,它将每次都被使用。
返回
route_from_har
Added in: v1.23如果指定,所做的网络请求将在上下文中从 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 不会处理从 HAR 文件中被 Service Worker 拦截的请求。请参见 此处 的问题。我们建议在使用请求拦截时禁用 Service Worker,通过将 service_workers 设置为 'block' 来实现。
🌐 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'.
用法
browser_context.route_from_har(har)
browser_context.route_from_har(har, **kwargs)
参数
-
harUnion[str, pathlib.Path]#指向包含预录网络数据的 HAR 文件的路径。如果
path是相对路径,则相对于当前工作目录进行解析。 -
not_found"abort" | "fallback" (optional)#- 如果设置为“中止”,任何在 HAR 文件中未找到的请求都将被中止。
- 如果设置为“fallback”,将会传递到处理链中的下一个路由处理程序。
默认为中止。
-
如果指定,会使用实际的网络信息更新给定的 HAR,而不是从文件提供。当调用 browser_context.close() 时,文件会写入磁盘。
-
update_content"embed" | "attach" (optional) Added in: v1.32#可选设置,用于控制资源内容管理。如果指定
attach,资源将作为单独的文件或 ZIP 压缩包中的条目进行保存。如果指定embed,内容将存储在 HAR 文件中。 -
update_mode"full" | "minimal" (optional) Added in: v1.32#当设置为
minimal时,仅记录从 HAR 路由所需的信息。这会省略在从 HAR 回放时不使用的大小、时间、页面、Cookies、安全性以及其他类型的 HAR 信息。默认值为minimal。 -
用于匹配请求 URL 的通配符模式、正则表达式或谓词。只有 URL 匹配该模式的请求才会从 HAR 文件中提供服务。如果未指定,则所有请求都将从 HAR 文件中提供服务。
返回
route_web_socket
Added in: v1.48此方法允许修改浏览器上下文中任何页面建立的 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.
用法
下面是一个简单处理程序的示例,它可以阻止某些 WebSocket 消息。有关更多详细信息和示例,请参见 WebSocketRoute。
🌐 Below is an example of a simple handler that blocks some websocket messages. See WebSocketRoute for more details and examples.
- Sync
- Async
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)
def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
if message == "to-be-blocked":
return
ws.send(message)
async def handler(ws: WebSocketRoute):
ws.route_send(lambda message: message_handler(ws, message))
await ws.connect()
await context.route_web_socket("/ws", handler)
参数
-
urlstr | Pattern | Callable[URL]:bool#只有 URL 符合此模式的 WebSocket 才会被路由。字符串模式可以相对于 base_url 上下文选项。
-
handlerCallable[WebSocketRoute]:Promise[Any] | Any#路由 WebSocket 的处理程序函数。
返回
set_default_navigation_timeout
Added before v1.9此设置将更改以下方法和相关快捷方式的默认最大导航时间:
🌐 This setting will change the default maximum navigation time for the following methods and related shortcuts:
- page.go_back()
- page.go_forward()
- page.goto()
- page.reload()
- page.set_content()
- page.expect_navigation()
用法
browser_context.set_default_navigation_timeout(timeout)
参数
set_default_timeout
Added before v1.9此设置将更改所有接受 timeout 选项的方法的默认最大时间。
🌐 This setting will change the default maximum time for all the methods accepting timeout option.
用法
browser_context.set_default_timeout(timeout)
参数
set_extra_http_headers
Added before v1.9额外的 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(headers)
参数
返回
set_geolocation
Added before v1.9设置上下文的地理位置。传入 null 或 undefined 会模拟位置不可用。
🌐 Sets the context's geolocation. Passing null or undefined emulates position unavailable.
用法
- Sync
- Async
browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667})
await 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.
参数
返回
set_offline
Added before v1.9用法
browser_context.set_offline(offline)
参数
返回
storage_state
Added before v1.9返回此浏览器上下文的存储状态,包含当前 cookie、本地存储快照和 IndexedDB 快照。
🌐 Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.
用法
browser_context.storage_state()
browser_context.storage_state(**kwargs)
参数
-
indexed_dbbool (optional) Added in: v1.51#设置为
true以在存储状态快照中包含 IndexedDB。如果你的应用使用 IndexedDB 来存储身份验证令牌,例如 Firebase 身份验证,请启用此选项。 -
pathUnion[str, pathlib.Path] (optional)#要保存存储状态的文件路径。如果path是相对路径,则相对于当前工作目录解析。如果未提供路径,存储状态仍然会返回,但不会保存到磁盘。
返回
unroute
Added before v1.9移除使用 browser_context.route() 创建的路由。当未指定 handler 时,会移除所有指定 url 的路由。
🌐 Removes a route created with browser_context.route(). When handler is not specified, removes all routes for the url.
用法
browser_context.unroute(url)
browser_context.unroute(url, **kwargs)
参数
-
urlstr | Pattern | Callable[URL]:bool#用于使用 browser_context.route() 注册路由的 glob 模式、正则表达式模式或接收 URL 的谓词。
-
handlerCallable[Route, Request]:Promise[Any] | Any (optional)#可选的处理函数,用于使用 browser_context.route() 注册路由。
返回
unroute_all
Added in: v1.41移除所有通过 browser_context.route() 和 browser_context.route_from_har() 创建的路由。
🌐 Removes all routes created with browser_context.route() and browser_context.route_from_har().
用法
browser_context.unroute_all()
browser_context.unroute_all(**kwargs)
参数
-
behavior"wait" | "ignoreErrors" | "default" (optional)#指定是否等待已经运行的处理程序以及如果它们抛出错误该怎么办:
'default'- 不要等待当前处理程序调用(如果有)完成,如果未路由的处理程序抛出异常,可能会导致未处理的错误'wait'- 等待当前处理程序的调用(如果有)完成'ignoreErrors'- 不要等待当前处理程序的调用(如果有)完成,在取消路由后,处理程序抛出的所有错误都会被静默捕获
返回
wait_for_event
Added before v1.9在大多数情况下,你应该使用 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.
用法
browser_context.wait_for_event(event)
browser_context.wait_for_event(event, **kwargs)
参数
-
事件名称,通常传递到
*.on(event)的那个相同名称。 -
predicateCallable (optional)#接收事件数据并在等待解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
属性
🌐 Properties
browser
Added before v1.9获取拥有该上下文的浏览器实例。如果上下文是在正常浏览器之外创建的,例如 Android 或 Electron,则返回 null。
🌐 Gets the browser instance that owns the context. Returns null if the context is created outside of normal browser, e.g. Android or Electron.
用法
browser_context.browser
返回
clock
Added in: v1.45Playwright 能够模拟时钟和时间的流逝。
🌐 Playwright has ability to mock clock and passage of time.
用法
browser_context.clock
类型
pages
Added before v1.9返回上下文中所有打开的页面。
🌐 Returns all open pages in the context.
用法
browser_context.pages
返回
request
Added in: v1.16与此上下文相关的 API 测试助手。使用此 API 发出的请求将使用上下文 Cookie。
🌐 API testing helper associated with this context. Requests made with this API will use context cookies.
用法
browser_context.request
类型
service_workers
Added in: v1.11服务工作者仅在基于 Chromium 的浏览器上受支持。
🌐 Service workers are only supported on Chromium-based browsers.
上下文中所有现有的 Service Worker。
🌐 All existing service workers in the context.
用法
browser_context.service_workers
返回
tracing
Added in: v1.12用法
browser_context.tracing
类型
事件
🌐 Events
on("close")
Added before v1.9当浏览器上下文被关闭时触发。这可能是以下原因之一导致的:
🌐 Emitted when Browser context gets closed. This might happen because of one of the following:
- 浏览器上下文已关闭。
- 浏览器应用已关闭或崩溃。
- 已调用 browser.close() 方法。
用法
browser_context.on("close", handler)
事件数据
on("console")
Added in: v1.34当页面中的 JavaScript 调用某个控制台 API 方法时触发,例如 console.log 或 console.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.
用法
- Sync
- Async
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' })")
async def print_args(msg):
values = []
for arg in msg.args:
values.append(await arg.json_value())
print(values)
context.on("console", print_args)
await page.evaluate("console.log('hello', 5, { foo: 'bar' })")
事件数据
on("dialog")
Added in: v1.34当出现 JavaScript 对话框时触发,例如 alert、prompt、confirm 或 beforeunload。监听器必须要么 dialog.accept(),要么 dialog.dismiss() 对话框——否则页面会冻结等待对话框,像点击这样的操作将永远无法完成。
🌐 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.
用法
context.on("dialog", lambda dialog: dialog.accept())
当没有[page.on(“dialog”)](/api/class-page.mdx#page-event-dialog)或[browser_context.on(“dialog”)](/api/class-browsercontext.mdx#browser-context-event-dialog)监听者时,所有对话都会自动被关闭。
事件数据
on("page")
Added before v1.9当在 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.
- Sync
- Async
with context.expect_page() as page_info:
page.get_by_text("open new page").click(),
page = page_info.value
print(page.evaluate("location.href"))
async with context.expect_page() as page_info:
await page.get_by_text("open new page").click(),
page = await page_info.value
print(await 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). :::
用法
browser_context.on("page", handler)
事件数据
on("request")
Added in: v1.12当从通过此上下文创建的任何页面发出请求时触发。 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().
用法
browser_context.on("request", handler)
事件数据
on("requestfailed")
Added in: v1.12当请求失败时触发,例如超时。要仅监听来自特定页面的失败请求,请使用 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").
用法
browser_context.on("requestfailed", handler)
事件数据
on("requestfinished")
Added in: v1.12当请求在下载响应主体后成功完成时触发。对于成功的响应,事件顺序是 request、response 和 requestfinished。要监听来自特定页面的成功请求,请使用 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").
用法
browser_context.on("requestfinished", handler)
事件数据
on("response")
Added in: v1.12当请求的 response 状态和头部被接收时触发。对于成功的响应,事件的顺序是 request、response 和 requestfinished。要监听来自特定页面的响应事件,请使用 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").
用法
browser_context.on("response", handler)
事件数据
on("serviceworker")
Added in: v1.11服务工作者仅在基于 Chromium 的浏览器上受支持。
🌐 Service workers are only supported on Chromium-based browsers.
在上下文中创建新的 Service Worker 时触发。
🌐 Emitted when new service worker is created in the context.
用法
browser_context.on("serviceworker", handler)
事件数据
on("weberror")
Added in: v1.38当在此上下文中的任何页面中未处理异常时,会触发此事件。要监听特定页面的错误,请改用 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.
用法
browser_context.on("weberror", handler)
事件数据
已弃用
🌐 Deprecated
on("backgroundpage")
Added in: v1.11后台页面已从 Chromium 中移除,同时 Manifest V2 扩展也已移除。
🌐 Background pages have been removed from Chromium together with Manifest V2 extensions.
此事件不会触发。
🌐 This event is not emitted.
用法
browser_context.on("backgroundpage", handler)
事件数据
background_pages
Added in: v1.11后台页面已从 Chromium 中移除,同时 Manifest V2 扩展也已移除。
🌐 Background pages have been removed from Chromium together with Manifest V2 extensions.
返回一个空列表。
🌐 Returns an empty list.
用法
browser_context.background_pages
返回