# Copyright (c) Microsoft Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import pathlib import typing from typing import Literal from playwright._impl._api_structures import ( BrowserBindResult, ClientCertificate, Cookie, DebuggerLocation, DebuggerPausedDetails, DropPayload, FilePayload, FloatRect, Geolocation, HttpCredentials, NameValue, PdfMargins, Position, ProxySettings, RemoteAddr, RequestSizes, ResourceTiming, ScreencastActionStyle, ScreencastFrame, ScreencastSize, SecurityDetails, SetCookieParam, SourceLocation, StorageState, TracingGroupLocation, ViewportSize, VirtualCredential, WebErrorLocation, WebMCPTool, ) from playwright._impl._assertions import ( APIResponseAssertions as APIResponseAssertionsImpl, ) from playwright._impl._assertions import LocatorAssertions as LocatorAssertionsImpl from playwright._impl._assertions import PageAssertions as PageAssertionsImpl from playwright._impl._browser import Browser as BrowserImpl from playwright._impl._browser_context import BrowserContext as BrowserContextImpl from playwright._impl._browser_type import BrowserType as BrowserTypeImpl from playwright._impl._cdp_session import CDPSession as CDPSessionImpl from playwright._impl._clock import Clock as ClockImpl from playwright._impl._console_message import ConsoleMessage as ConsoleMessageImpl from playwright._impl._credentials import Credentials as CredentialsImpl from playwright._impl._debugger import Debugger as DebuggerImpl from playwright._impl._dialog import Dialog as DialogImpl from playwright._impl._disposable import Disposable as DisposableImpl from playwright._impl._download import Download as DownloadImpl from playwright._impl._element_handle import ElementHandle as ElementHandleImpl from playwright._impl._errors import Error from playwright._impl._fetch import APIRequest as APIRequestImpl from playwright._impl._fetch import APIRequestContext as APIRequestContextImpl from playwright._impl._fetch import APIResponse as APIResponseImpl from playwright._impl._file_chooser import FileChooser as FileChooserImpl from playwright._impl._form_data import FormData from playwright._impl._frame import Frame as FrameImpl from playwright._impl._helper import to_milliseconds from playwright._impl._input import Keyboard as KeyboardImpl from playwright._impl._input import Mouse as MouseImpl from playwright._impl._input import Touchscreen as TouchscreenImpl from playwright._impl._js_handle import JSHandle as JSHandleImpl from playwright._impl._locator import FrameLocator as FrameLocatorImpl from playwright._impl._locator import Locator as LocatorImpl from playwright._impl._network import Request as RequestImpl from playwright._impl._network import Response as ResponseImpl from playwright._impl._network import Route as RouteImpl from playwright._impl._network import WebSocket as WebSocketImpl from playwright._impl._network import WebSocketRoute as WebSocketRouteImpl from playwright._impl._page import Page as PageImpl from playwright._impl._page import Worker as WorkerImpl from playwright._impl._playwright import Playwright as PlaywrightImpl from playwright._impl._screencast import Screencast as ScreencastImpl from playwright._impl._selectors import Selectors as SelectorsImpl from playwright._impl._sync_base import ( EventContextManager, SyncBase, SyncContextManager, mapping, ) from playwright._impl._tracing import Tracing as TracingImpl from playwright._impl._video import Video as VideoImpl from playwright._impl._web_error import WebError as WebErrorImpl from playwright._impl._web_storage import WebStorage as WebStorageImpl from playwright._impl._webmcp import WebMCP as WebMCPImpl class APIRequest(SyncBase): _impl_obj: APIRequestImpl def new_context( self, *, base_url: typing.Optional[str] = None, client_certificates: typing.Optional[typing.Sequence[ClientCertificate]] = None, extra_http_headers: typing.Optional[typing.Dict[str, str]] = None, fail_on_status_code: typing.Optional[bool] = None, http_credentials: typing.Optional[ typing.Union[HttpCredentials, typing.Sequence[HttpCredentials]] ] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, proxy: typing.Optional[ProxySettings] = None, storage_state: typing.Optional[ typing.Union[str, pathlib.Path, StorageState] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, user_agent: typing.Optional[str] = None, ) -> "APIRequestContext": """APIRequest.new_context Creates new instances of `APIRequestContext`. Parameters ---------- base_url : Union[str, None] Methods like `api_request_context.get()` take the base URL into consideration by using the [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL. Examples: - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html` - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in `http://localhost:3000/foo/bar.html` - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in `http://localhost:3000/bar.html` client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None] TLS Client Authentication allows the server to request a client certificate and verify it. **Details** 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. Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that does not match any of the domains you plan to visit. **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it work by replacing `localhost` with `local.playwright`. extra_http_headers : Union[Dict[str, str], None] An object containing additional HTTP headers to be sent with every request. Defaults to none. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. http_credentials : Union[Sequence[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}], {username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None] Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no origin is specified, the username and password are sent to any servers upon unauthorized responses. Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request individually. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None] Network proxy settings. storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}, None] Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via `browser_context.storage_state()` or `api_request_context.storage_state()`. Either a path to the file with saved storage, or the value returned by one of `browser_context.storage_state()` or `api_request_context.storage_state()` methods. timeout : Union[float, None] Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. user_agent : Union[str, None] Specific user agent to use in this context. Returns ------- APIRequestContext """ return mapping.from_impl( self._sync( self._impl_obj.new_context( baseURL=base_url, clientCertificates=mapping.to_impl(client_certificates), extraHTTPHeaders=mapping.to_impl(extra_http_headers), failOnStatusCode=fail_on_status_code, httpCredentials=mapping.to_impl(http_credentials), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, proxy=proxy, storageState=storage_state, timeout=to_milliseconds(timeout), userAgent=user_agent, ) ) ) mapping.register(APIRequestImpl, APIRequest) class APIRequestContext(SyncBase): _impl_obj: APIRequestContextImpl def add_cookies(self, cookies: typing.Sequence[SetCookieParam]) -> None: """APIRequestContext.add_cookies Adds cookies into this request context. They will be sent with matching subsequent requests. For `browser_context.request` and `page.request`, this is equivalent to calling `browser_context.add_cookies()` on the corresponding browser context. **Usage** ```py request.add_cookies([cookie_object1, cookie_object2]) ``` Parameters ---------- cookies : Sequence[{name: str, value: str, url: Union[str, None], domain: Union[str, None], path: Union[str, None], expires: Union[float, None], httpOnly: Union[bool, None], secure: Union[bool, None], sameSite: Union["Lax", "None", "Strict", None], partitionKey: Union[str, None]}] """ self._sync(self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies))) def clear_cookies( self, *, domain: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, name: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, path: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, ) -> None: """APIRequestContext.clear_cookies Removes cookies from this request context. Accepts optional filter. For `browser_context.request` and `page.request`, this is equivalent to calling `browser_context.clear_cookies()` on the corresponding browser context. **Usage** ```py request.clear_cookies() request.clear_cookies(name=\"session-id\") request.clear_cookies(domain=\"my-origin.com\") request.clear_cookies(path=\"/api/v1\") request.clear_cookies(name=\"session-id\", domain=\"my-origin.com\") ``` Parameters ---------- domain : Union[Pattern[str], str, None] Only removes cookies with the given domain. name : Union[Pattern[str], str, None] Only removes cookies with the given name. path : Union[Pattern[str], str, None] Only removes cookies with the given path. """ self._sync(self._impl_obj.clear_cookies(domain=domain, name=name, path=path)) def cookies( self, urls: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None ) -> typing.List[Cookie]: """APIRequestContext.cookies If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned. For `browser_context.request` and `page.request`, this is equivalent to calling `browser_context.cookies()` on the corresponding browser context. Parameters ---------- urls : Union[Sequence[str], str, None] Optional list of URLs. Returns ------- List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}] """ return mapping.from_impl_list( self._sync(self._impl_obj.cookies(urls=mapping.to_impl(urls))) ) def delete( self, url: str, *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.delete Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. Parameters ---------- url : str Target URL. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.delete( url=url, data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def dispose(self, *, reason: typing.Optional[str] = None) -> None: """APIRequestContext.dispose All responses returned by `api_request_context.get()` and similar methods are stored in the memory, so that you can later call `api_response.body()`.This method discards all its resources, calling any method on disposed `APIRequestContext` will throw an exception. Parameters ---------- reason : Union[str, None] The reason to be reported to the operations interrupted by the context disposal. """ self._sync(self._impl_obj.dispose(reason=reason)) def fetch( self, url_or_request: typing.Union[str, "Request"], *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, method: typing.Optional[str] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.fetch Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. **Usage** JSON objects can be passed directly to the request: ```python data = { \"title\": \"Book Title\", \"body\": \"John Doe\", } api_request_context.fetch(\"https://example.com/api/createBook\", method=\"post\", data=data) ``` The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data` encoding, by specifiying the `multipart` parameter: ```python api_request_context.fetch( \"https://example.com/api/uploadScript\", method=\"post\", multipart={ \"fileField\": { \"name\": \"f.js\", \"mimeType\": \"text/javascript\", \"buffer\": b\"console.log(2022);\", }, }) ``` Parameters ---------- url_or_request : Union[Request, str] Target URL or Request to get all parameters from. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. method : Union[str, None] If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.fetch( urlOrRequest=mapping.to_impl(url_or_request), data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, method=method, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def get( self, url: str, *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.get Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. **Usage** Request parameters can be configured with `params` option, they will be serialized into the URL search parameters: ```python query_params = { \"isbn\": \"1234\", \"page\": \"23\" } api_request_context.get(\"https://example.com/api/getText\", params=query_params) ``` Parameters ---------- url : str Target URL. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.get( url=url, data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def head( self, url: str, *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.head Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. Parameters ---------- url : str Target URL. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.head( url=url, data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def patch( self, url: str, *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.patch Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. Parameters ---------- url : str Target URL. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.patch( url=url, data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def post( self, url: str, *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.post Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. **Usage** JSON objects can be passed directly to the request: ```python data = { \"title\": \"Book Title\", \"body\": \"John Doe\", } api_request_context.post(\"https://example.com/api/createBook\", data=data) ``` To send form data to the server use `form` option. Its value will be encoded into the request body with `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send files): ```python formData = { \"title\": \"Book Title\", \"body\": \"John Doe\", } api_request_context.post(\"https://example.com/api/findBook\", form=formData) ``` The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data` encoding. Use `FormData` to construct request body and pass it to the request as `multipart` parameter: ```python api_request_context.post( \"https://example.com/api/uploadScript'\", multipart={ \"fileField\": { \"name\": \"f.js\", \"mimeType\": \"text/javascript\", \"buffer\": b\"console.log(2022);\", }, }) ``` Parameters ---------- url : str Target URL. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.post( url=url, data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def put( self, url: str, *, data: typing.Optional[typing.Union[str, bytes, typing.Any]] = None, fail_on_status_code: typing.Optional[bool] = None, form: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], "FormData"] ] = None, headers: typing.Optional[typing.Dict[str, str]] = None, ignore_https_errors: typing.Optional[bool] = None, max_redirects: typing.Optional[int] = None, max_retries: typing.Optional[int] = None, multipart: typing.Optional[ typing.Union[ typing.Dict[str, typing.Union[str, float, bool, bytes, FilePayload]], "FormData", ] ] = None, params: typing.Optional[ typing.Union[typing.Dict[str, typing.Union[str, float, bool]], str] ] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "APIResponse": """APIRequestContext.put Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. Parameters ---------- url : str Target URL. data : Union[Any, bytes, str, None] Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be set to `application/octet-stream` if not explicitly set. fail_on_status_code : Union[bool, None] Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes. form : Union[Dict[str, Union[bool, float, str]], FormData, None] Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `application/x-www-form-urlencoded` unless explicitly provided. Use `FormData` to send multiple values for the same field. headers : Union[Dict[str, str], None] Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. max_redirects : Union[int, None] Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to `20`. Pass `0` to not follow redirects. max_retries : Union[int, None] Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries. multipart : Union[Dict[str, Union[bool, bytes, float, str, {name: str, mimeType: str, buffer: bytes}]], FormData, None] Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content. Use `FormData` to send multiple files in the same field. params : Union[Dict[str, Union[bool, float, str]], str, None] Query parameters to be sent with the URL. timeout : Union[float, None] Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- APIResponse """ return mapping.from_impl( self._sync( self._impl_obj.put( url=url, data=mapping.to_impl(data), failOnStatusCode=fail_on_status_code, form=mapping.to_impl(form), headers=mapping.to_impl(headers), ignoreHTTPSErrors=ignore_https_errors, maxRedirects=max_redirects, maxRetries=max_retries, multipart=mapping.to_impl(multipart), params=mapping.to_impl(params), timeout=to_milliseconds(timeout), ) ) ) def storage_state( self, *, indexed_db: typing.Optional[bool] = None, opfs: typing.Optional[bool] = None, path: typing.Optional[typing.Union[str, pathlib.Path]] = None, ) -> StorageState: """APIRequestContext.storage_state Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor. Parameters ---------- indexed_db : Union[bool, None] Set to `true` to include IndexedDB in the storage state snapshot. opfs : Union[bool, None] Set to `true` to include the origin private file system in the storage state snapshot. path : Union[pathlib.Path, str, None] 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 ------- {cookies: List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: List[{origin: str, localStorage: List[{name: str, value: str}]}]} """ return mapping.from_impl( self._sync( self._impl_obj.storage_state(indexedDB=indexed_db, opfs=opfs, path=path) ) ) @property def tracing(self) -> "Tracing": """APIRequestContext.tracing Tracing recorder for requests made through this API request context. Returns ------- Tracing """ return mapping.from_impl(self._impl_obj.tracing) mapping.register(APIRequestContextImpl, APIRequestContext) class APIResponse(SyncBase): _impl_obj: APIResponseImpl def body(self) -> bytes: """APIResponse.body Returns the buffer with response body. Returns ------- bytes """ return mapping.from_maybe_impl(self._sync(self._impl_obj.body())) def dispose(self) -> None: """APIResponse.dispose Disposes the body of this response. If not called then the body will stay in memory until the context closes. """ self._sync(self._impl_obj.dispose()) @property def headers(self) -> typing.Dict[str, str]: """APIResponse.headers An object with all the response HTTP headers associated with this response. Returns ------- Dict[str, str] """ return mapping.from_maybe_impl(self._impl_obj.headers) @property def headers_array(self) -> typing.List[NameValue]: """APIResponse.headers_array An array with all the response HTTP headers associated with this response. Header names are not lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times. Returns ------- List[{name: str, value: str}] """ return mapping.from_impl_list(self._impl_obj.headers_array) def json(self) -> typing.Any: """APIResponse.json Returns the JSON representation of response body. This method will throw if the response body is not parsable via `JSON.parse`. Returns ------- Any """ return mapping.from_maybe_impl(self._sync(self._impl_obj.json())) @property def ok(self) -> bool: """APIResponse.ok Contains a boolean stating whether the response was successful (status in the range 200-299) or not. Returns ------- bool """ return mapping.from_maybe_impl(self._impl_obj.ok) def security_details(self) -> typing.Optional[SecurityDetails]: """APIResponse.security_details Returns SSL and other security information. Resolves to `null` for non-HTTPS responses. For redirected requests, returns the information for the last request in the redirect chain. Returns ------- Union[{issuer: Union[str, None], protocol: Union[str, None], subjectName: Union[str, None], validFrom: Union[float, None], validTo: Union[float, None]}, None] """ return mapping.from_impl_nullable(self._sync(self._impl_obj.security_details())) def server_addr(self) -> typing.Optional[RemoteAddr]: """APIResponse.server_addr Returns the IP address and port of the server. Resolves to `null` if the server address is not available. For redirected requests, returns the information for the last request in the redirect chain. Returns ------- Union[{ipAddress: str, port: int}, None] """ return mapping.from_impl_nullable(self._sync(self._impl_obj.server_addr())) @property def status(self) -> int: """APIResponse.status Contains the status code of the response (e.g., 200 for a success). Returns ------- int """ return mapping.from_maybe_impl(self._impl_obj.status) @property def status_text(self) -> str: """APIResponse.status_text Contains the status text of the response (e.g. usually an \"OK\" for a success). Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.status_text) def text(self) -> str: """APIResponse.text Returns the text representation of response body. Returns ------- str """ return mapping.from_maybe_impl(self._sync(self._impl_obj.text())) @property def timing(self) -> ResourceTiming: """APIResponse.timing Returns resource timing information for given response. For redirected requests, returns the information for the last request in the redirect chain. When the response is served [from the HAR file](https://playwright.dev/python/docs/mock#replaying-from-har), timing information is not available and all the values are -1. Find more information at [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming). Returns ------- {startTime: float, domainLookupStart: float, domainLookupEnd: float, connectStart: float, secureConnectionStart: float, connectEnd: float, requestStart: float, responseStart: float, responseEnd: float} """ return mapping.from_impl(self._impl_obj.timing) @property def url(self) -> str: """APIResponse.url Contains the URL of the response. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.url) mapping.register(APIResponseImpl, APIResponse) class APIResponseAssertions(SyncBase): _impl_obj: APIResponseAssertionsImpl def not_to_be_ok(self) -> None: """APIResponseAssertions.not_to_be_ok The opposite of `api_response_assertions.to_be_ok()`. """ __tracebackhide__ = True self._sync(self._impl_obj.not_to_be_ok()) def to_be_ok(self) -> None: """APIResponseAssertions.to_be_ok Ensures the response status code is within `200..299` range. **Usage** ```py import re from playwright.sync_api import expect # ... expect(response).to_be_ok() ``` """ __tracebackhide__ = True self._sync(self._impl_obj.to_be_ok()) mapping.register(APIResponseAssertionsImpl, APIResponseAssertions) class Browser(SyncContextManager): _impl_obj: BrowserImpl def bind( self, title: str, *, host: typing.Optional[str] = None, port: typing.Optional[int] = None, workspace_dir: typing.Optional[str] = None, ) -> BrowserBindResult: """Browser.bind Binds the browser to a named pipe or web socket, making it available for other clients to connect to. Parameters ---------- title : str Title of the browser server, used for identification. host : Union[str, None] Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. port : Union[int, None] Port to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. Use `0` to let the OS pick an available port. workspace_dir : Union[str, None] Working directory associated with this browser server. Returns ------- {endpoint: str} """ return mapping.from_impl( self._sync( self._impl_obj.bind( title=title, host=host, port=port, workspaceDir=workspace_dir ) ) ) @property def browser_type(self) -> "BrowserType": """Browser.browser_type Get the browser type (chromium, firefox or webkit) that the browser belongs to. Returns ------- BrowserType """ return mapping.from_impl(self._impl_obj.browser_type) def close(self, *, reason: typing.Optional[str] = None) -> None: """Browser.close In case this browser is obtained using `browser_type.launch()`, closes the browser and all of its pages (if any were opened). In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the browser server. **NOTE** This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close events, call `browser_context.close()` on any `BrowserContext` instances you explicitly created earlier using `browser.new_context()` **before** calling `browser.close()`. The `Browser` object itself is considered to be disposed and cannot be used anymore. Parameters ---------- reason : Union[str, None] The reason to be reported to the operations interrupted by the browser closure. """ self._sync(self._impl_obj.close(reason=reason)) @property def contexts(self) -> typing.List["BrowserContext"]: """Browser.contexts Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts. **Usage** ```py browser = pw.webkit.launch() print(len(browser.contexts)) # prints `0` context = browser.new_context() print(len(browser.contexts)) # prints `1` ``` Returns ------- List[BrowserContext] """ return mapping.from_impl_list(self._impl_obj.contexts) def is_connected(self) -> bool: """Browser.is_connected Indicates that the browser is connected. Returns ------- bool """ return mapping.from_maybe_impl(self._impl_obj.is_connected()) def new_browser_cdp_session(self) -> "CDPSession": """Browser.new_browser_cdp_session **NOTE** CDP Sessions are only supported on Chromium-based browsers. Returns the newly created browser session. Returns ------- CDPSession """ return mapping.from_impl(self._sync(self._impl_obj.new_browser_cdp_session())) def new_context( self, *, accept_downloads: typing.Optional[bool] = None, base_url: typing.Optional[str] = None, bypass_csp: typing.Optional[bool] = None, client_certificates: typing.Optional[typing.Sequence[ClientCertificate]] = None, color_scheme: typing.Optional[ Literal["dark", "light", "no-preference", "null"] ] = None, contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None, default_browser_type: typing.Optional[str] = None, device_scale_factor: typing.Optional[float] = None, extra_http_headers: typing.Optional[typing.Dict[str, str]] = None, forced_colors: typing.Optional[Literal["active", "none", "null"]] = None, geolocation: typing.Optional[Geolocation] = None, has_touch: typing.Optional[bool] = None, http_credentials: typing.Optional[ typing.Union[HttpCredentials, typing.Sequence[HttpCredentials]] ] = None, ignore_https_errors: typing.Optional[bool] = None, is_mobile: typing.Optional[bool] = None, java_script_enabled: typing.Optional[bool] = None, locale: typing.Optional[str] = None, no_viewport: typing.Optional[bool] = None, offline: typing.Optional[bool] = None, permissions: typing.Optional[typing.Sequence[str]] = None, proxy: typing.Optional[ProxySettings] = None, record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None, record_har_mode: typing.Optional[Literal["full", "minimal"]] = None, record_har_omit_content: typing.Optional[bool] = None, record_har_path: typing.Optional[typing.Union[str, pathlib.Path]] = None, record_har_url_filter: typing.Optional[ typing.Union[str, typing.Pattern[str]] ] = None, record_video_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, record_video_fps: typing.Optional[int] = None, record_video_size: typing.Optional[ViewportSize] = None, reduced_motion: typing.Optional[ Literal["no-preference", "null", "reduce"] ] = None, screen: typing.Optional[ViewportSize] = None, service_workers: typing.Optional[Literal["allow", "block"]] = None, storage_state: typing.Optional[ typing.Union[str, pathlib.Path, StorageState] ] = None, strict_selectors: typing.Optional[bool] = None, timezone_id: typing.Optional[str] = None, user_agent: typing.Optional[str] = None, viewport: typing.Optional[ViewportSize] = None, ) -> "BrowserContext": """Browser.new_context Creates a new browser context. It won't share cookies/cache with other browser contexts. **NOTE** If directly using this method to create `BrowserContext`s, it is best practice to explicitly close the returned context via `browser_context.close()` when your code is done with the `BrowserContext`, and before calling `browser.close()`. This will ensure the `context` is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved. **Usage** ```py browser = playwright.firefox.launch() # or \"chromium\" or \"webkit\". # create a new incognito browser context. context = browser.new_context() # create a new page in a pristine context. page = context.new_page() page.goto(\"https://example.com\") # gracefully close up everything context.close() browser.close() ``` Parameters ---------- accept_downloads : Union[bool, None] Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted. base_url : Union[str, None] 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()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL. Unset by default. Examples: - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html` - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in `http://localhost:3000/foo/bar.html` - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in `http://localhost:3000/bar.html` bypass_csp : Union[bool, None] Toggles bypassing page's Content-Security-Policy. Defaults to `false`. client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None] TLS Client Authentication allows the server to request a client certificate and verify it. **Details** 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. Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that does not match any of the domains you plan to visit. **NOTE** 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 : Union["dark", "light", "no-preference", "null", None] Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-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 : Union["more", "no-preference", "null", None] 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'`. device_scale_factor : Union[float, None] Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about [emulating devices with device scale factor](../emulation.md#devices). extra_http_headers : Union[Dict[str, str], None] An object containing additional HTTP headers to be sent with every request. Defaults to none. forced_colors : Union["active", "none", "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'`. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None] has_touch : Union[bool, None] Specifies if viewport supports touch events. Defaults to false. Learn more about [mobile emulation](../emulation.md#devices). http_credentials : Union[Sequence[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}], {username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None] Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no origin is specified, the username and password are sent to any servers upon unauthorized responses. Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. is_mobile : Union[bool, None] 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`. Learn more about [mobile emulation](../emulation.md#ismobile). java_script_enabled : Union[bool, None] Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about [disabling JavaScript](../emulation.md#javascript-enabled). locale : Union[str, None] 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](../emulation.md#locale--timezone). no_viewport : Union[bool, None] Does not enforce fixed viewport, allows resizing window in the headed mode. offline : Union[bool, None] Whether to emulate network being offline. Defaults to `false`. Learn more about [network emulation](../emulation.md#offline). permissions : Union[Sequence[str], None] A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for more details. Defaults to none. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None] Network proxy settings to use with this context. Defaults to none. record_har_content : Union["attach", "embed", "omit", None] Optional setting to control resource content management. If `omit` is specified, content is not persisted. If `attach` is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification. record_har_mode : Union["full", "minimal", None] When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`. record_har_omit_content : Union[bool, None] Optional setting to control whether to omit request content from the HAR. Defaults to `false`. record_har_path : Union[pathlib.Path, str, None] Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) 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_har_url_filter : Union[Pattern[str], str, None] record_video_dir : Union[pathlib.Path, str, None] 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. record_video_fps : Union[int, None] Frame rate of the recorded videos in frames per second. Defaults to `25`. Firefox and WebKit currently capture up to 25 frames per second. record_video_size : Union[{width: int, height: int}, None] 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 : Union["no-preference", "null", "reduce", None] 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'`. screen : Union[{width: int, height: int}, None] Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport` is set. service_workers : Union["allow", "block", None] Whether to allow sites to register Service workers. Defaults to `'allow'`. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be registered. - `'block'`: Playwright will block all registration of Service Workers. storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}, None] Learn more about [storage state and auth](../auth.md). Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via `browser_context.storage_state()`. strict_selectors : Union[bool, None] 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. timezone_id : Union[str, None] Changes the timezone of the context. See [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs. Defaults to the system timezone. user_agent : Union[str, None] Specific user agent to use in this context. viewport : Union[{width: int, height: int}, None] Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed viewport. Learn more about [viewport emulation](../emulation.md#viewport). Returns ------- BrowserContext """ return mapping.from_impl( self._sync( self._impl_obj.new_context( acceptDownloads=accept_downloads, baseURL=base_url, bypassCSP=bypass_csp, clientCertificates=mapping.to_impl(client_certificates), colorScheme=color_scheme, contrast=contrast, defaultBrowserType=default_browser_type, deviceScaleFactor=device_scale_factor, extraHTTPHeaders=mapping.to_impl(extra_http_headers), forcedColors=forced_colors, geolocation=geolocation, hasTouch=has_touch, httpCredentials=mapping.to_impl(http_credentials), ignoreHTTPSErrors=ignore_https_errors, isMobile=is_mobile, javaScriptEnabled=java_script_enabled, locale=locale, noViewport=no_viewport, offline=offline, permissions=mapping.to_impl(permissions), proxy=proxy, recordHarContent=record_har_content, recordHarMode=record_har_mode, recordHarOmitContent=record_har_omit_content, recordHarPath=record_har_path, recordHarUrlFilter=record_har_url_filter, recordVideoDir=record_video_dir, recordVideoFps=record_video_fps, recordVideoSize=record_video_size, reducedMotion=reduced_motion, screen=screen, serviceWorkers=service_workers, storageState=storage_state, strictSelectors=strict_selectors, timezoneId=timezone_id, userAgent=user_agent, viewport=viewport, ) ) ) def new_page( self, *, accept_downloads: typing.Optional[bool] = None, base_url: typing.Optional[str] = None, bypass_csp: typing.Optional[bool] = None, client_certificates: typing.Optional[typing.Sequence[ClientCertificate]] = None, color_scheme: typing.Optional[ Literal["dark", "light", "no-preference", "null"] ] = None, contrast: typing.Optional[Literal["more", "no-preference", "null"]] = None, default_browser_type: typing.Optional[str] = None, device_scale_factor: typing.Optional[float] = None, extra_http_headers: typing.Optional[typing.Dict[str, str]] = None, forced_colors: typing.Optional[Literal["active", "none", "null"]] = None, geolocation: typing.Optional[Geolocation] = None, has_touch: typing.Optional[bool] = None, http_credentials: typing.Optional[ typing.Union[HttpCredentials, typing.Sequence[HttpCredentials]] ] = None, ignore_https_errors: typing.Optional[bool] = None, is_mobile: typing.Optional[bool] = None, java_script_enabled: typing.Optional[bool] = None, locale: typing.Optional[str] = None, no_viewport: typing.Optional[bool] = None, offline: typing.Optional[bool] = None, permissions: typing.Optional[typing.Sequence[str]] = None, proxy: typing.Optional[ProxySettings] = None, record_har_content: typing.Optional[Literal["attach", "embed", "omit"]] = None, record_har_mode: typing.Optional[Literal["full", "minimal"]] = None, record_har_omit_content: typing.Optional[bool] = None, record_har_path: typing.Optional[typing.Union[str, pathlib.Path]] = None, record_har_url_filter: typing.Optional[ typing.Union[str, typing.Pattern[str]] ] = None, record_video_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, record_video_fps: typing.Optional[int] = None, record_video_size: typing.Optional[ViewportSize] = None, reduced_motion: typing.Optional[ Literal["no-preference", "null", "reduce"] ] = None, screen: typing.Optional[ViewportSize] = None, service_workers: typing.Optional[Literal["allow", "block"]] = None, storage_state: typing.Optional[ typing.Union[str, pathlib.Path, StorageState] ] = None, strict_selectors: typing.Optional[bool] = None, timezone_id: typing.Optional[str] = None, user_agent: typing.Optional[str] = None, viewport: typing.Optional[ViewportSize] = None, ) -> "Page": """Browser.new_page Creates a new page in a new browser context. Closing this page will close the context as well. This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and testing frameworks should explicitly create `browser.new_context()` followed by the `browser_context.new_page()` to control their exact life times. Parameters ---------- accept_downloads : Union[bool, None] Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted. base_url : Union[str, None] 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()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL. Unset by default. Examples: - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html` - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in `http://localhost:3000/foo/bar.html` - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in `http://localhost:3000/bar.html` bypass_csp : Union[bool, None] Toggles bypassing page's Content-Security-Policy. Defaults to `false`. client_certificates : Union[Sequence[{origin: str, certPath: Union[pathlib.Path, str, None], cert: Union[bytes, None], keyPath: Union[pathlib.Path, str, None], key: Union[bytes, None], pfxPath: Union[pathlib.Path, str, None], pfx: Union[bytes, None], passphrase: Union[str, None]}], None] TLS Client Authentication allows the server to request a client certificate and verify it. **Details** 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. Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that does not match any of the domains you plan to visit. **NOTE** 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 : Union["dark", "light", "no-preference", "null", None] Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-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 : Union["more", "no-preference", "null", None] 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'`. device_scale_factor : Union[float, None] Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about [emulating devices with device scale factor](../emulation.md#devices). extra_http_headers : Union[Dict[str, str], None] An object containing additional HTTP headers to be sent with every request. Defaults to none. forced_colors : Union["active", "none", "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'`. geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None] has_touch : Union[bool, None] Specifies if viewport supports touch events. Defaults to false. Learn more about [mobile emulation](../emulation.md#devices). http_credentials : Union[Sequence[{username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}], {username: str, password: str, origin: Union[str, None], send: Union["always", "unauthorized", None]}, None] Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no origin is specified, the username and password are sent to any servers upon unauthorized responses. Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request. ignore_https_errors : Union[bool, None] Whether to ignore HTTPS errors when sending network requests. Defaults to `false`. is_mobile : Union[bool, None] 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`. Learn more about [mobile emulation](../emulation.md#ismobile). java_script_enabled : Union[bool, None] Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about [disabling JavaScript](../emulation.md#javascript-enabled). locale : Union[str, None] 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](../emulation.md#locale--timezone). no_viewport : Union[bool, None] Does not enforce fixed viewport, allows resizing window in the headed mode. offline : Union[bool, None] Whether to emulate network being offline. Defaults to `false`. Learn more about [network emulation](../emulation.md#offline). permissions : Union[Sequence[str], None] A list of permissions to grant to all pages in this context. See `browser_context.grant_permissions()` for more details. Defaults to none. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None] Network proxy settings to use with this context. Defaults to none. record_har_content : Union["attach", "embed", "omit", None] Optional setting to control resource content management. If `omit` is specified, content is not persisted. If `attach` is specified, resources are persisted as separate files and all of these files are archived along with the HAR file. Defaults to `embed`, which stores content inline the HAR file as per HAR specification. record_har_mode : Union["full", "minimal", None] When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`. record_har_omit_content : Union[bool, None] Optional setting to control whether to omit request content from the HAR. Defaults to `false`. record_har_path : Union[pathlib.Path, str, None] Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) 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_har_url_filter : Union[Pattern[str], str, None] record_video_dir : Union[pathlib.Path, str, None] 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. record_video_fps : Union[int, None] Frame rate of the recorded videos in frames per second. Defaults to `25`. Firefox and WebKit currently capture up to 25 frames per second. record_video_size : Union[{width: int, height: int}, None] 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 : Union["no-preference", "null", "reduce", None] 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'`. screen : Union[{width: int, height: int}, None] Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport` is set. service_workers : Union["allow", "block", None] Whether to allow sites to register Service workers. Defaults to `'allow'`. - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be registered. - `'block'`: Playwright will block all registration of Service Workers. storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}, None] Learn more about [storage state and auth](../auth.md). Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via `browser_context.storage_state()`. strict_selectors : Union[bool, None] 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. timezone_id : Union[str, None] Changes the timezone of the context. See [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs. Defaults to the system timezone. user_agent : Union[str, None] Specific user agent to use in this context. viewport : Union[{width: int, height: int}, None] Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `no_viewport` disables the fixed viewport. Learn more about [viewport emulation](../emulation.md#viewport). Returns ------- Page """ return mapping.from_impl( self._sync( self._impl_obj.new_page( acceptDownloads=accept_downloads, baseURL=base_url, bypassCSP=bypass_csp, clientCertificates=mapping.to_impl(client_certificates), colorScheme=color_scheme, contrast=contrast, defaultBrowserType=default_browser_type, deviceScaleFactor=device_scale_factor, extraHTTPHeaders=mapping.to_impl(extra_http_headers), forcedColors=forced_colors, geolocation=geolocation, hasTouch=has_touch, httpCredentials=mapping.to_impl(http_credentials), ignoreHTTPSErrors=ignore_https_errors, isMobile=is_mobile, javaScriptEnabled=java_script_enabled, locale=locale, noViewport=no_viewport, offline=offline, permissions=mapping.to_impl(permissions), proxy=proxy, recordHarContent=record_har_content, recordHarMode=record_har_mode, recordHarOmitContent=record_har_omit_content, recordHarPath=record_har_path, recordHarUrlFilter=record_har_url_filter, recordVideoDir=record_video_dir, recordVideoFps=record_video_fps, recordVideoSize=record_video_size, reducedMotion=reduced_motion, screen=screen, serviceWorkers=service_workers, storageState=storage_state, strictSelectors=strict_selectors, timezoneId=timezone_id, userAgent=user_agent, viewport=viewport, ) ) ) @typing.overload def on( self, event: Literal["context"], f: typing.Callable[["BrowserContext"], "None"] ) -> None: """ Emitted when a new browser context is created.""" @typing.overload def on( self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "None"] ) -> None: """ Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following: - Browser application is closed or crashed. - The `browser.close()` method was called.""" def on(self, event: str, f: typing.Callable[..., None]) -> None: return super().on(event=event, f=f) @typing.overload def once( self, event: Literal["context"], f: typing.Callable[["BrowserContext"], "None"] ) -> None: """ Emitted when a new browser context is created.""" @typing.overload def once( self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "None"] ) -> None: """ Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following: - Browser application is closed or crashed. - The `browser.close()` method was called.""" def once(self, event: str, f: typing.Callable[..., None]) -> None: return super().once(event=event, f=f) def start_tracing( self, *, categories: typing.Optional[typing.Sequence[str]] = None, page: typing.Optional["Page"] = None, path: typing.Optional[typing.Union[str, pathlib.Path]] = None, screenshots: typing.Optional[bool] = None, ) -> None: """Browser.start_tracing **NOTE** This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found [here](https://playwright.dev/python/docs/api/class-tracing). You can use `browser.start_tracing()` and `browser.stop_tracing()` to create a trace file that can be opened in Chrome DevTools performance panel. **Usage** ```py browser.start_tracing(page, path=\"trace.json\") page.goto(\"https://www.google.com\") browser.stop_tracing() ``` Parameters ---------- categories : Union[Sequence[str], None] specify custom categories to use instead of default. page : Union[Page, None] Optional, if specified, tracing includes screenshots of the given page. path : Union[pathlib.Path, str, None] A path to write the trace file to. screenshots : Union[bool, None] captures screenshots in the trace. """ self._sync( self._impl_obj.start_tracing( categories=mapping.to_impl(categories), page=page._impl_obj if page else None, path=path, screenshots=screenshots, ) ) def stop_tracing(self) -> bytes: """Browser.stop_tracing **NOTE** This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](https://playwright.dev/python/docs/trace-viewer) could be found [here](https://playwright.dev/python/docs/api/class-tracing). Returns the buffer with trace data. Returns ------- bytes """ return mapping.from_maybe_impl(self._sync(self._impl_obj.stop_tracing())) def unbind(self) -> None: """Browser.unbind Unbinds the browser server previously bound with `browser.bind()`. """ self._sync(self._impl_obj.unbind()) @property def version(self) -> str: """Browser.version Returns the browser version. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.version) mapping.register(BrowserImpl, Browser) class BrowserContext(SyncContextManager): _impl_obj: BrowserContextImpl def add_cookies(self, cookies: typing.Sequence[SetCookieParam]) -> None: """BrowserContext.add_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** ```py browser_context.add_cookies([cookie_object1, cookie_object2]) ``` Parameters ---------- cookies : Sequence[{name: str, value: str, url: Union[str, None], domain: Union[str, None], path: Union[str, None], expires: Union[float, None], httpOnly: Union[bool, None], secure: Union[bool, None], sameSite: Union["Lax", "None", "Strict", None], partitionKey: Union[str, None]}] """ self._sync(self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies))) def add_init_script( self, script: typing.Optional[str] = None, *, path: typing.Optional[typing.Union[str, pathlib.Path]] = None, ) -> "SyncContextManager": """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. 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** An example of overriding `Math.random` before the page loads: ```py # in your playwright script, assuming the preload.js file is in same directory. browser_context.add_init_script(path=\"preload.js\") ``` **NOTE** The order of evaluation of multiple scripts installed via `browser_context.add_init_script()` and `page.add_init_script()` is not defined. Parameters ---------- script : Union[str, None] Script to be evaluated in all pages in the browser context. Optional. path : Union[pathlib.Path, str, None] Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional. Returns ------- SyncContextManager """ return mapping.from_impl( self._sync(self._impl_obj.add_init_script(script=script, path=path)) ) @property def background_pages(self) -> typing.List["Page"]: """BrowserContext.background_pages Returns an empty list. Returns ------- List[Page] """ return mapping.from_impl_list(self._impl_obj.background_pages) @property def browser(self) -> typing.Optional["Browser"]: """BrowserContext.browser Gets the browser instance that owns the context. Returns `null` if the context is created outside of normal browser, e.g. Android or Electron. Returns ------- Union[Browser, None] """ return mapping.from_impl_nullable(self._impl_obj.browser) def clear_cookies( self, *, domain: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, name: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, path: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, ) -> None: """BrowserContext.clear_cookies Removes cookies from context. Accepts optional filter. **Usage** ```py 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\") ``` Parameters ---------- domain : Union[Pattern[str], str, None] Only removes cookies with the given domain. name : Union[Pattern[str], str, None] Only removes cookies with the given name. path : Union[Pattern[str], str, None] Only removes cookies with the given path. """ self._sync(self._impl_obj.clear_cookies(domain=domain, name=name, path=path)) def clear_permissions(self) -> None: """BrowserContext.clear_permissions Clears all permission overrides for the browser context. **Usage** ```py context = browser.new_context() context.grant_permissions([\"clipboard-read\"]) # do stuff .. context.clear_permissions() ``` """ self._sync(self._impl_obj.clear_permissions()) @property def clock(self) -> "Clock": """BrowserContext.clock Playwright has ability to mock clock and passage of time. Returns ------- Clock """ return mapping.from_impl(self._impl_obj.clock) def close(self, *, reason: typing.Optional[str] = None) -> None: """BrowserContext.close Closes the browser context. All the pages that belong to the browser context will be closed. **NOTE** The default browser context cannot be closed. Parameters ---------- reason : Union[str, None] The reason to be reported to the operations interrupted by the context closure. """ self._sync(self._impl_obj.close(reason=reason)) def cookies( self, urls: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None ) -> typing.List[Cookie]: """BrowserContext.cookies If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned. Parameters ---------- urls : Union[Sequence[str], str, None] Optional list of URLs. Returns ------- List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}] """ return mapping.from_impl_list( self._sync(self._impl_obj.cookies(urls=mapping.to_impl(urls))) ) @property def credentials(self) -> "Credentials": """BrowserContext.credentials Virtual WebAuthn authenticator for this context. Lets tests seed credentials and intercept `navigator.credentials.create()` / `navigator.credentials.get()` ceremonies. Returns ------- Credentials """ return mapping.from_impl(self._impl_obj.credentials) @property def debugger(self) -> "Debugger": """BrowserContext.debugger Debugger allows to pause and resume the execution. Returns ------- Debugger """ return mapping.from_impl(self._impl_obj.debugger) def expect_console_message( self, predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None, *, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> EventContextManager["ConsoleMessage"]: """BrowserContext.expect_console_message 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. Parameters ---------- predicate : Union[Callable[[ConsoleMessage], bool], None] Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve. timeout : Union[float, None] 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 ------- EventContextManager[ConsoleMessage] """ return EventContextManager( self, self._impl_obj.expect_console_message( predicate=self._wrap_handler(predicate), timeout=to_milliseconds(timeout), ).future, ) @typing.overload def expect_event( self, event: typing.Literal["backgroundpage"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["close"], predicate: typing.Optional[typing.Callable[["BrowserContext"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["BrowserContext"]: ... @typing.overload def expect_event( self, event: typing.Literal["console"], predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["ConsoleMessage"]: ... @typing.overload def expect_event( self, event: typing.Literal["dialog"], predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Dialog"]: ... @typing.overload def expect_event( self, event: typing.Literal["dialogclosed"], predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Dialog"]: ... @typing.overload def expect_event( self, event: typing.Literal["download"], predicate: typing.Optional[typing.Callable[["Download"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Download"]: ... @typing.overload def expect_event( self, event: typing.Literal["frameattached"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Frame"]: ... @typing.overload def expect_event( self, event: typing.Literal["framedetached"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Frame"]: ... @typing.overload def expect_event( self, event: typing.Literal["framenavigated"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Frame"]: ... @typing.overload def expect_event( self, event: typing.Literal["page"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["pageclose"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["pageload"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["request"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Request"]: ... @typing.overload def expect_event( self, event: typing.Literal["requestfailed"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Request"]: ... @typing.overload def expect_event( self, event: typing.Literal["requestfinished"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Request"]: ... @typing.overload def expect_event( self, event: typing.Literal["response"], predicate: typing.Optional[typing.Callable[["Response"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Response"]: ... @typing.overload def expect_event( self, event: typing.Literal["serviceworker"], predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["Worker"]: ... @typing.overload def expect_event( self, event: typing.Literal["weberror"], predicate: typing.Optional[typing.Callable[["WebError"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager["WebError"]: ... @typing.overload def expect_event( self, event: str, predicate: typing.Optional[typing.Callable[..., bool]] = None, *, timeout: typing.Optional[float] = None, ) -> EventContextManager[typing.Any]: ... def expect_event( self, event: str, predicate: typing.Optional[typing.Callable] = None, *, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> EventContextManager: """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** ```py with context.expect_event(\"page\") as event_info: page.get_by_role(\"button\").click() page = event_info.value ``` Parameters ---------- event : str Event name, same one would pass into `browserContext.on(event)`. predicate : Union[Callable, None] Receives the event data and resolves to truthy value when the waiting should resolve. timeout : Union[float, None] 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 ------- EventContextManager """ return EventContextManager( self, self._impl_obj.expect_event( event=event, predicate=self._wrap_handler(predicate), timeout=to_milliseconds(timeout), ).future, ) def expect_page( self, predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> EventContextManager["Page"]: """BrowserContext.expect_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. Parameters ---------- predicate : Union[Callable[[Page], bool], None] Receives the `Page` object and resolves to truthy value when the waiting should resolve. timeout : Union[float, None] 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 ------- EventContextManager[Page] """ return EventContextManager( self, self._impl_obj.expect_page( predicate=self._wrap_handler(predicate), timeout=to_milliseconds(timeout), ).future, ) def expose_binding( self, name: str, callback: typing.Callable ) -> "SyncContextManager": """BrowserContext.expose_binding 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. The first argument of the `callback` function contains information about the caller: `{ browserContext: BrowserContext, page: Page, frame: Frame }`. See `page.expose_binding()` for page-only version. **Usage** An example of exposing page URL to all frames in all pages in the context: ```py 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(\"\"\"
\"\"\") page.get_by_role(\"button\").click() with sync_playwright() as playwright: run(playwright) ``` Parameters ---------- name : str Name of the function on the window object. callback : Callable Callback function that will be called in the Playwright's context. Returns ------- SyncContextManager """ return mapping.from_impl( self._sync( self._impl_obj.expose_binding( name=name, callback=self._wrap_handler(callback) ) ) ) def expose_function( self, name: str, callback: typing.Callable ) -> "SyncContextManager": """BrowserContext.expose_function 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. See `page.expose_function()` for page-only version. **Usage** An example of adding a `sha256` function to all pages in the context: ```py 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(\"\"\" \"\"\") page.get_by_role(\"button\").click() with sync_playwright() as playwright: run(playwright) ``` Parameters ---------- name : str Name of the function on the window object. callback : Callable Callback function that will be called in the Playwright's context. Returns ------- SyncContextManager """ return mapping.from_impl( self._sync( self._impl_obj.expose_function( name=name, callback=self._wrap_handler(callback) ) ) ) def grant_permissions( self, permissions: typing.Sequence[str], *, origin: typing.Optional[str] = None ) -> None: """BrowserContext.grant_permissions Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified. Parameters ---------- permissions : Sequence[str] A list of permissions to grant. **NOTE** 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'` - `'local-fonts'` - `'local-network-access'` - `'magnetometer'` - `'microphone'` - `'midi-sysex'` (system-exclusive midi) - `'midi'` - `'notifications'` - `'payment-handler'` - `'storage-access'` - `'screen-wake-lock'` origin : Union[str, None] The [origin] to grant permissions to, e.g. "https://example.com". """ self._sync( self._impl_obj.grant_permissions( permissions=mapping.to_impl(permissions), origin=origin ) ) def is_closed(self) -> bool: """BrowserContext.is_closed Indicates that the browser context is in the process of closing or has already been closed. Returns ------- bool """ return mapping.from_maybe_impl(self._impl_obj.is_closed()) def new_cdp_session(self, page: typing.Union["Page", "Frame"]) -> "CDPSession": """BrowserContext.new_cdp_session **NOTE** CDP sessions are only supported on Chromium-based browsers. Returns the newly created session. Parameters ---------- page : Union[Frame, Page] Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a `Page` or `Frame` type. Returns ------- CDPSession """ return mapping.from_impl( self._sync(self._impl_obj.new_cdp_session(page=mapping.to_impl(page))) ) def new_page(self) -> "Page": """BrowserContext.new_page Creates a new page in the browser context. Returns ------- Page """ return mapping.from_impl(self._sync(self._impl_obj.new_page())) @typing.overload def on( self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "None"] ) -> None: """ This event is not emitted.""" @typing.overload def on( self, event: Literal["close"], f: typing.Callable[["BrowserContext"], "None"] ) -> None: """ 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. - The `browser.close()` method was called.""" @typing.overload def on( self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"] ) -> None: """ Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument. **Usage** ```py 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' })\") ```""" @typing.overload def on( self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"] ) -> None: """ 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog, and actions like click will never finish. **Usage** ```python context.on(\"dialog\", lambda dialog: dialog.accept()) ``` **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are automatically dismissed.""" @typing.overload def on( self, event: Literal["dialogclosed"], f: typing.Callable[["Dialog"], "None"] ) -> None: """ Emitted when a JavaScript dialog in any page belonging to this context has been closed, either by `dialog.accept()`, by `dialog.dismiss()`, or manually by the user in the headed browser. """ @typing.overload def on( self, event: Literal["download"], f: typing.Callable[["Download"], "None"] ) -> None: """ Emitted when attachment download started in any page belonging to this context. User can access basic file operations on downloaded content via the passed `Download` instance. See also `page.on('download')` to receive events about a specific page.""" @typing.overload def on( self, event: Literal["frameattached"], f: typing.Callable[["Frame"], "None"] ) -> None: """ Emitted when a frame is attached in any page belonging to this context. See also `page.on('frameattached')` to receive events about a specific page.""" @typing.overload def on( self, event: Literal["framedetached"], f: typing.Callable[["Frame"], "None"] ) -> None: """ Emitted when a frame is detached in any page belonging to this context. See also `page.on('framedetached')` to receive events about a specific page.""" @typing.overload def on( self, event: Literal["framenavigated"], f: typing.Callable[["Frame"], "None"] ) -> None: """ Emitted when a frame is navigated to a new url in any page belonging to this context. See also `page.on('framenavigated')` to receive events about navigations in a specific page. """ @typing.overload def on(self, event: Literal["page"], f: typing.Callable[["Page"], "None"]) -> None: """ 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. 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`. ```py with context.expect_page() as page_info: page.get_by_text(\"open new page\").click(), page = page_info.value print(page.evaluate(\"location.href\")) ``` **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not need it in most cases).""" @typing.overload def on( self, event: Literal["pageclose"], f: typing.Callable[["Page"], "None"] ) -> None: """ Emitted when a page in this context is closed. See also `page.on('close')` to receive events about a specific page. """ @typing.overload def on( self, event: Literal["pageload"], f: typing.Callable[["Page"], "None"] ) -> None: """ Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched in any page belonging to this context. See also `page.on('load')` to receive events about a specific page. """ @typing.overload def on( self, event: Literal["request"], f: typing.Callable[["Request"], "None"] ) -> None: """ 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')`. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`. """ @typing.overload def on( self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"] ) -> None: """ Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use `page.on('requestfailed')`. **NOTE** 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')`.""" @typing.overload def on( self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"] ) -> None: """ 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')`.""" @typing.overload def on( self, event: Literal["response"], f: typing.Callable[["Response"], "None"] ) -> None: """ 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')`.""" @typing.overload def on( self, event: Literal["serviceworker"], f: typing.Callable[["Worker"], "None"] ) -> None: """ **NOTE** Service workers are only supported on Chromium-based browsers. Emitted when new service worker is created in the context.""" @typing.overload def on( self, event: Literal["weberror"], f: typing.Callable[["WebError"], "None"] ) -> None: """ 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.""" def on(self, event: str, f: typing.Callable[..., None]) -> None: return super().on(event=event, f=f) @typing.overload def once( self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "None"] ) -> None: """ This event is not emitted.""" @typing.overload def once( self, event: Literal["close"], f: typing.Callable[["BrowserContext"], "None"] ) -> None: """ 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. - The `browser.close()` method was called.""" @typing.overload def once( self, event: Literal["console"], f: typing.Callable[["ConsoleMessage"], "None"] ) -> None: """ Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument. **Usage** ```py 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' })\") ```""" @typing.overload def once( self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "None"] ) -> None: """ 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog, and actions like click will never finish. **Usage** ```python context.on(\"dialog\", lambda dialog: dialog.accept()) ``` **NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are automatically dismissed.""" @typing.overload def once( self, event: Literal["dialogclosed"], f: typing.Callable[["Dialog"], "None"] ) -> None: """ Emitted when a JavaScript dialog in any page belonging to this context has been closed, either by `dialog.accept()`, by `dialog.dismiss()`, or manually by the user in the headed browser. """ @typing.overload def once( self, event: Literal["download"], f: typing.Callable[["Download"], "None"] ) -> None: """ Emitted when attachment download started in any page belonging to this context. User can access basic file operations on downloaded content via the passed `Download` instance. See also `page.on('download')` to receive events about a specific page.""" @typing.overload def once( self, event: Literal["frameattached"], f: typing.Callable[["Frame"], "None"] ) -> None: """ Emitted when a frame is attached in any page belonging to this context. See also `page.on('frameattached')` to receive events about a specific page.""" @typing.overload def once( self, event: Literal["framedetached"], f: typing.Callable[["Frame"], "None"] ) -> None: """ Emitted when a frame is detached in any page belonging to this context. See also `page.on('framedetached')` to receive events about a specific page.""" @typing.overload def once( self, event: Literal["framenavigated"], f: typing.Callable[["Frame"], "None"] ) -> None: """ Emitted when a frame is navigated to a new url in any page belonging to this context. See also `page.on('framenavigated')` to receive events about navigations in a specific page. """ @typing.overload def once( self, event: Literal["page"], f: typing.Callable[["Page"], "None"] ) -> None: """ 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. 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`. ```py with context.expect_page() as page_info: page.get_by_text(\"open new page\").click(), page = page_info.value print(page.evaluate(\"location.href\")) ``` **NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not need it in most cases).""" @typing.overload def once( self, event: Literal["pageclose"], f: typing.Callable[["Page"], "None"] ) -> None: """ Emitted when a page in this context is closed. See also `page.on('close')` to receive events about a specific page. """ @typing.overload def once( self, event: Literal["pageload"], f: typing.Callable[["Page"], "None"] ) -> None: """ Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched in any page belonging to this context. See also `page.on('load')` to receive events about a specific page. """ @typing.overload def once( self, event: Literal["request"], f: typing.Callable[["Request"], "None"] ) -> None: """ 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')`. In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`. """ @typing.overload def once( self, event: Literal["requestfailed"], f: typing.Callable[["Request"], "None"] ) -> None: """ Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use `page.on('requestfailed')`. **NOTE** 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')`.""" @typing.overload def once( self, event: Literal["requestfinished"], f: typing.Callable[["Request"], "None"] ) -> None: """ 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')`.""" @typing.overload def once( self, event: Literal["response"], f: typing.Callable[["Response"], "None"] ) -> None: """ 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')`.""" @typing.overload def once( self, event: Literal["serviceworker"], f: typing.Callable[["Worker"], "None"] ) -> None: """ **NOTE** Service workers are only supported on Chromium-based browsers. Emitted when new service worker is created in the context.""" @typing.overload def once( self, event: Literal["weberror"], f: typing.Callable[["WebError"], "None"] ) -> None: """ 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.""" def once(self, event: str, f: typing.Callable[..., None]) -> None: return super().once(event=event, f=f) @property def pages(self) -> typing.List["Page"]: """BrowserContext.pages Returns all open pages in the context. Returns ------- List[Page] """ return mapping.from_impl_list(self._impl_obj.pages) @property def request(self) -> "APIRequestContext": """BrowserContext.request API testing helper associated with this context. Requests made with this API will use context cookies. Returns ------- APIRequestContext """ return mapping.from_impl(self._impl_obj.request) def route( self, url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]], handler: typing.Union[ typing.Callable[["Route"], typing.Any], typing.Callable[["Route", "Request"], typing.Any], ], *, times: typing.Optional[int] = None, ) -> "SyncContextManager": """BrowserContext.route 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. **NOTE** `browser_context.route()` will not intercept requests intercepted by Service Worker. See [this](https://github.com/microsoft/playwright/issues/1090) 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: ```py 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: ```py 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: ```py 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 routes (set up with `page.route()`) take precedence over browser context routes when request matches both handlers. To remove a route with its handler you can use `browser_context.unroute()`. **NOTE** Enabling routing disables http cache. Parameters ---------- url : Union[Callable[[str], bool], Pattern[str], str] 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()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]] handler function to route the request. times : Union[int, None] How often a route should be used. By default it will be used every time. Returns ------- SyncContextManager """ return mapping.from_impl( self._sync( self._impl_obj.route( url=self._wrap_handler(url), handler=self._wrap_handler(handler), times=times, ) ) ) def route_from_har( self, har: typing.Union[str, pathlib.Path], *, not_found: typing.Optional[Literal["abort", "fallback"]] = None, update: typing.Optional[bool] = None, update_content: typing.Optional[Literal["attach", "embed"]] = None, update_mode: typing.Optional[Literal["full", "minimal"]] = None, url: typing.Optional[typing.Union[str, typing.Pattern[str]]] = None, ) -> None: """BrowserContext.route_from_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](https://playwright.dev/python/docs/mock#replaying-from-har). Playwright will not serve requests intercepted by Service Worker from the HAR file. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting `service_workers` to `'block'`. Parameters ---------- har : Union[pathlib.Path, str] Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a relative path, then it is resolved relative to the current working directory. not_found : Union["abort", "fallback", None] - If set to 'abort' any request not found in the HAR file will be aborted. - If set to 'fallback' falls through to the next route handler in the handler chain. Defaults to abort. update : Union[bool, None] 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 : Union["attach", "embed", None] 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 : Union["full", "minimal", None] 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 : Union[Pattern[str], str, None] 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. """ self._sync( self._impl_obj.route_from_har( har=har, notFound=not_found, update=update, updateContent=update_content, updateMode=update_mode, url=url, ) ) def route_web_socket( self, url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]], handler: typing.Callable[["WebSocketRoute"], typing.Any], ) -> None: """BrowserContext.route_web_socket This method allows to modify websocket connections that are made by any page in the browser context. Note that only `WebSocket`s created after this method was called will be routed. It is recommended to call this method before creating any pages. **Usage** Below is an example of a simple handler that blocks some websocket messages. See `WebSocketRoute` for more details and examples. ```py 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) ``` Parameters ---------- url : Union[Callable[[str], bool], Pattern[str], str] Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the `base_url` context option. handler : Callable[[WebSocketRoute], Any] Handler function to route the WebSocket. """ self._sync( self._impl_obj.route_web_socket( url=self._wrap_handler(url), handler=self._wrap_handler(handler) ) ) @property def service_workers(self) -> typing.List["Worker"]: """BrowserContext.service_workers **NOTE** Service workers are only supported on Chromium-based browsers. All existing service workers in the context. Returns ------- List[Worker] """ return mapping.from_impl_list(self._impl_obj.service_workers) def set_default_navigation_timeout( self, timeout: typing.Union[float, datetime.timedelta] ) -> None: """BrowserContext.set_default_navigation_timeout 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()` **NOTE** `page.set_default_navigation_timeout()` and `page.set_default_timeout()` take priority over `browser_context.set_default_navigation_timeout()`. Parameters ---------- timeout : float Maximum navigation time in milliseconds """ self._impl_obj.set_default_navigation_timeout(timeout=to_milliseconds(timeout)) def set_default_timeout( self, timeout: typing.Union[float, datetime.timedelta] ) -> None: """BrowserContext.set_default_timeout This setting will change the default maximum time for all the methods accepting `timeout` option. **NOTE** `page.set_default_navigation_timeout()`, `page.set_default_timeout()` and `browser_context.set_default_navigation_timeout()` take priority over `browser_context.set_default_timeout()`. Parameters ---------- timeout : float Maximum time in milliseconds. Pass `0` to disable timeout. """ self._impl_obj.set_default_timeout(timeout=to_milliseconds(timeout)) def set_extra_http_headers(self, headers: typing.Dict[str, str]) -> None: """BrowserContext.set_extra_http_headers 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. **NOTE** `browser_context.set_extra_http_headers()` does not guarantee the order of headers in the outgoing requests. Parameters ---------- headers : Dict[str, str] An object containing additional HTTP headers to be sent with every request. All header values must be strings. """ self._sync( self._impl_obj.set_extra_http_headers(headers=mapping.to_impl(headers)) ) def set_geolocation(self, geolocation: typing.Optional[Geolocation] = None) -> None: """BrowserContext.set_geolocation Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable. **Usage** ```py browser_context.set_geolocation({\"latitude\": 59.95, \"longitude\": 30.31667}) ``` **NOTE** Consider using `browser_context.grant_permissions()` to grant permissions for the browser context pages to read its geolocation. Parameters ---------- geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None] """ self._sync(self._impl_obj.set_geolocation(geolocation=geolocation)) def set_offline(self, offline: bool) -> None: """BrowserContext.set_offline Parameters ---------- offline : bool Whether to emulate network being offline for the browser context. **NOTE** Offline emulation only affects requests that go through the browser's regular network stack, such as page navigations, `fetch()`, `XMLHttpRequest` and WebSockets. It does not affect WebRTC traffic: established `RTCPeerConnection`s keep sending and receiving media over UDP. To test WebRTC connection loss, interrupt the connection outside the browser, for example by stopping the TURN server or using an OS-level firewall. """ self._sync(self._impl_obj.set_offline(offline=offline)) def set_storage_state( self, storage_state: typing.Union[str, pathlib.Path, StorageState] ) -> None: """BrowserContext.set_storage_state Clears the existing cookies, local storage, IndexedDB entries, origin private file system entries and virtual WebAuthn credentials, and sets the new storage state. When the storage state contains credentials, the virtual WebAuthn authenticator is installed (equivalent to `credentials.install()`), preventing all real authenticators from working in this context. **Usage** ```py # Load storage state from a file and apply it to the context. context.set_storage_state(\"state.json\") ``` Parameters ---------- storage_state : Union[pathlib.Path, str, {cookies: Sequence[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: Sequence[{origin: str, localStorage: Sequence[{name: str, value: str}]}]}] Learn more about [storage state and auth](../auth.md). Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via `browser_context.storage_state()`. """ self._sync(self._impl_obj.set_storage_state(storageState=storage_state)) def storage_state( self, *, credentials: typing.Optional[bool] = None, indexed_db: typing.Optional[bool] = None, opfs: typing.Optional[bool] = None, path: typing.Optional[typing.Union[str, pathlib.Path]] = None, ) -> StorageState: """BrowserContext.storage_state Returns storage state for this browser context, contains current cookies, local storage snapshot, IndexedDB snapshot, origin private file system snapshot and virtual WebAuthn credentials. Parameters ---------- credentials : Union[bool, None] Set to `true` to include the context's virtual WebAuthn `browser_context.credentials` (passkeys) in the storage state snapshot. The captured credentials carry their private keys and signature counters, so they can be re-seeded into a later context via the `storage_state` option or `browser_context.set_storage_state()`. Note that restoring the storage state that contains credentials will automatically install the virtual WebAuthn authenticator (see `credentials.install()`), and prevent all real authenticators from working in this context. indexed_db : Union[bool, None] Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this. opfs : Union[bool, None] Set to `true` to include the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system) in the storage state snapshot. **NOTE** OPFS is currently not supported in ephemeral WebKit contexts. path : Union[pathlib.Path, str, None] 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 ------- {cookies: List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: List[{origin: str, localStorage: List[{name: str, value: str}]}]} """ return mapping.from_impl( self._sync( self._impl_obj.storage_state( credentials=credentials, indexedDB=indexed_db, opfs=opfs, path=path ) ) ) @property def tracing(self) -> "Tracing": """BrowserContext.tracing Returns ------- Tracing """ return mapping.from_impl(self._impl_obj.tracing) def unroute( self, url: typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]], handler: typing.Optional[ typing.Union[ typing.Callable[["Route"], typing.Any], typing.Callable[["Route", "Request"], typing.Any], ] ] = None, ) -> None: """BrowserContext.unroute Removes a route created with `browser_context.route()`. When `handler` is not specified, removes all routes for the `url`. Parameters ---------- url : Union[Callable[[str], bool], Pattern[str], str] A glob pattern, regex pattern, or predicate receiving [URL] used to register a routing with `browser_context.route()`. handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None] Optional handler function used to register a routing with `browser_context.route()`. """ self._sync( self._impl_obj.unroute( url=self._wrap_handler(url), handler=self._wrap_handler(handler) ) ) def unroute_all( self, *, behavior: typing.Optional[Literal["default", "ignoreErrors", "wait"]] = None, ) -> None: """BrowserContext.unroute_all Removes all routes created with `browser_context.route()` and `browser_context.route_from_har()`. Parameters ---------- behavior : Union["default", "ignoreErrors", "wait", None] Specifies whether to wait for already running handlers and what to do if they throw errors: - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may result in unhandled error - `'wait'` - wait for current handler calls (if any) to finish - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught """ self._sync(self._impl_obj.unroute_all(behavior=behavior)) @typing.overload def wait_for_event( self, event: typing.Literal["backgroundpage"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Page": ... @typing.overload def wait_for_event( self, event: typing.Literal["close"], predicate: typing.Optional[typing.Callable[["BrowserContext"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "BrowserContext": ... @typing.overload def wait_for_event( self, event: typing.Literal["console"], predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "ConsoleMessage": ... @typing.overload def wait_for_event( self, event: typing.Literal["dialog"], predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Dialog": ... @typing.overload def wait_for_event( self, event: typing.Literal["dialogclosed"], predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Dialog": ... @typing.overload def wait_for_event( self, event: typing.Literal["download"], predicate: typing.Optional[typing.Callable[["Download"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Download": ... @typing.overload def wait_for_event( self, event: typing.Literal["frameattached"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Frame": ... @typing.overload def wait_for_event( self, event: typing.Literal["framedetached"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Frame": ... @typing.overload def wait_for_event( self, event: typing.Literal["framenavigated"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Frame": ... @typing.overload def wait_for_event( self, event: typing.Literal["page"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Page": ... @typing.overload def wait_for_event( self, event: typing.Literal["pageclose"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Page": ... @typing.overload def wait_for_event( self, event: typing.Literal["pageload"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Page": ... @typing.overload def wait_for_event( self, event: typing.Literal["request"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Request": ... @typing.overload def wait_for_event( self, event: typing.Literal["requestfailed"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Request": ... @typing.overload def wait_for_event( self, event: typing.Literal["requestfinished"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Request": ... @typing.overload def wait_for_event( self, event: typing.Literal["response"], predicate: typing.Optional[typing.Callable[["Response"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Response": ... @typing.overload def wait_for_event( self, event: typing.Literal["serviceworker"], predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "Worker": ... @typing.overload def wait_for_event( self, event: typing.Literal["weberror"], predicate: typing.Optional[typing.Callable[["WebError"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> "WebError": ... @typing.overload def wait_for_event( self, event: str, predicate: typing.Optional[typing.Callable[..., bool]] = None, *, timeout: typing.Optional[float] = None, ) -> typing.Any: ... def wait_for_event( self, event: str, predicate: typing.Optional[typing.Callable] = None, *, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> typing.Any: """BrowserContext.wait_for_event **NOTE** In most cases, you should use `browser_context.expect_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. Parameters ---------- event : str Event name, same one typically passed into `*.on(event)`. predicate : Union[Callable, None] Receives the event data and resolves to truthy value when the waiting should resolve. timeout : Union[float, None] 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 ------- Any """ return mapping.from_maybe_impl( self._sync( self._impl_obj.wait_for_event( event=event, predicate=self._wrap_handler(predicate), timeout=to_milliseconds(timeout), ) ) ) mapping.register(BrowserContextImpl, BrowserContext) class BrowserType(SyncBase): _impl_obj: BrowserTypeImpl def connect( self, endpoint: str, *, expose_network: typing.Optional[str] = None, headers: typing.Optional[typing.Dict[str, str]] = None, slow_mo: typing.Optional[float] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "Browser": """BrowserType.connect This method attaches Playwright to an existing browser instance created via `BrowserType.launchServer` in Node.js. **NOTE** 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). Parameters ---------- endpoint : str A Playwright browser websocket endpoint to connect to. You obtain this endpoint via `BrowserServer.wsEndpoint`. expose_network : Union[str, None] This option exposes network available on the connecting client to the browser being connected to. Consists of a list of rules separated by comma. Available rules: 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`. 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`. 1. `