# 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._async_base import ( AsyncBase, AsyncContextManager, AsyncEventContextManager, mapping, ) 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._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(AsyncBase): _impl_obj: APIRequestImpl async 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( await 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(AsyncBase): _impl_obj: APIRequestContextImpl async 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 await 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]}] """ await self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies)) async 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 await request.clear_cookies() await request.clear_cookies(name=\"session-id\") await request.clear_cookies(domain=\"my-origin.com\") await request.clear_cookies(path=\"/api/v1\") await 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. """ await self._impl_obj.clear_cookies(domain=domain, name=name, path=path) async 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( await self._impl_obj.cookies(urls=mapping.to_impl(urls)) ) async 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( await 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), ) ) async 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. """ await self._impl_obj.dispose(reason=reason) async 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( await 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), ) ) async 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( await 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), ) ) async 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( await 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), ) ) async 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( await 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), ) ) async 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( await 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), ) ) async 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( await 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), ) ) async 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( await 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(AsyncBase): _impl_obj: APIResponseImpl async def body(self) -> bytes: """APIResponse.body Returns the buffer with response body. Returns ------- bytes """ return mapping.from_maybe_impl(await self._impl_obj.body()) async 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. """ await 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) async 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(await 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) async 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(await self._impl_obj.security_details()) async 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(await 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) async def text(self) -> str: """APIResponse.text Returns the text representation of response body. Returns ------- str """ return mapping.from_maybe_impl(await 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(AsyncBase): _impl_obj: APIResponseAssertionsImpl async def not_to_be_ok(self) -> None: """APIResponseAssertions.not_to_be_ok The opposite of `api_response_assertions.to_be_ok()`. """ __tracebackhide__ = True await self._impl_obj.not_to_be_ok() async def to_be_ok(self) -> None: """APIResponseAssertions.to_be_ok Ensures the response status code is within `200..299` range. **Usage** ```py from playwright.async_api import expect # ... await expect(response).to_be_ok() ``` """ __tracebackhide__ = True await self._impl_obj.to_be_ok() mapping.register(APIResponseAssertionsImpl, APIResponseAssertions) class Browser(AsyncContextManager): _impl_obj: BrowserImpl async 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( await 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) async 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. """ await 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 = await pw.webkit.launch() print(len(browser.contexts)) # prints `0` context = await 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()) async 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(await self._impl_obj.new_browser_cdp_session()) async 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 = await playwright.firefox.launch() # or \"chromium\" or \"webkit\". # create a new incognito browser context. context = await browser.new_context() # create a new page in a pristine context. page = await context.new_page() await page.goto(\"https://example.com\") # gracefully close up everything await context.close() await 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( await 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, ) ) async 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( await 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"], "typing.Union[typing.Awaitable[None], None]" ], ) -> None: """ Emitted when a new browser context is created.""" @typing.overload def on( self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "typing.Union[typing.Awaitable[None], 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[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().on(event=event, f=f) @typing.overload def once( self, event: Literal["context"], f: typing.Callable[ ["BrowserContext"], "typing.Union[typing.Awaitable[None], None]" ], ) -> None: """ Emitted when a new browser context is created.""" @typing.overload def once( self, event: Literal["disconnected"], f: typing.Callable[["Browser"], "typing.Union[typing.Awaitable[None], 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[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().once(event=event, f=f) async 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 await browser.start_tracing(page, path=\"trace.json\") await page.goto(\"https://www.google.com\") await 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. """ await self._impl_obj.start_tracing( categories=mapping.to_impl(categories), page=page._impl_obj if page else None, path=path, screenshots=screenshots, ) async 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(await self._impl_obj.stop_tracing()) async def unbind(self) -> None: """Browser.unbind Unbinds the browser server previously bound with `browser.bind()`. """ await 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(AsyncContextManager): _impl_obj: BrowserContextImpl async 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 await 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]}] """ await self._impl_obj.add_cookies(cookies=mapping.to_impl(cookies)) async def add_init_script( self, script: typing.Optional[str] = None, *, path: typing.Optional[typing.Union[str, pathlib.Path]] = None, ) -> "AsyncContextManager": """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. await 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 ------- AsyncContextManager """ return mapping.from_impl( await 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) async 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 await context.clear_cookies() await context.clear_cookies(name=\"session-id\") await context.clear_cookies(domain=\"my-origin.com\") await context.clear_cookies(path=\"/api/v1\") await context.clear_cookies(name=\"session-id\", domain=\"my-origin.com\") ``` 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. """ await self._impl_obj.clear_cookies(domain=domain, name=name, path=path) async def clear_permissions(self) -> None: """BrowserContext.clear_permissions Clears all permission overrides for the browser context. **Usage** ```py context = await browser.new_context() await context.grant_permissions([\"clipboard-read\"]) # do stuff .. context.clear_permissions() ``` """ await 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) async 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. """ await self._impl_obj.close(reason=reason) async 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( await 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, ) -> AsyncEventContextManager["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 AsyncEventContextManager( 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, ) -> AsyncEventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["close"], predicate: typing.Optional[typing.Callable[["BrowserContext"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["BrowserContext"]: ... @typing.overload def expect_event( self, event: typing.Literal["console"], predicate: typing.Optional[typing.Callable[["ConsoleMessage"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["ConsoleMessage"]: ... @typing.overload def expect_event( self, event: typing.Literal["dialog"], predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Dialog"]: ... @typing.overload def expect_event( self, event: typing.Literal["dialogclosed"], predicate: typing.Optional[typing.Callable[["Dialog"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Dialog"]: ... @typing.overload def expect_event( self, event: typing.Literal["download"], predicate: typing.Optional[typing.Callable[["Download"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Download"]: ... @typing.overload def expect_event( self, event: typing.Literal["frameattached"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Frame"]: ... @typing.overload def expect_event( self, event: typing.Literal["framedetached"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Frame"]: ... @typing.overload def expect_event( self, event: typing.Literal["framenavigated"], predicate: typing.Optional[typing.Callable[["Frame"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Frame"]: ... @typing.overload def expect_event( self, event: typing.Literal["page"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["pageclose"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["pageload"], predicate: typing.Optional[typing.Callable[["Page"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Page"]: ... @typing.overload def expect_event( self, event: typing.Literal["request"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Request"]: ... @typing.overload def expect_event( self, event: typing.Literal["requestfailed"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Request"]: ... @typing.overload def expect_event( self, event: typing.Literal["requestfinished"], predicate: typing.Optional[typing.Callable[["Request"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Request"]: ... @typing.overload def expect_event( self, event: typing.Literal["response"], predicate: typing.Optional[typing.Callable[["Response"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Response"]: ... @typing.overload def expect_event( self, event: typing.Literal["serviceworker"], predicate: typing.Optional[typing.Callable[["Worker"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["Worker"]: ... @typing.overload def expect_event( self, event: typing.Literal["weberror"], predicate: typing.Optional[typing.Callable[["WebError"], bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager["WebError"]: ... @typing.overload def expect_event( self, event: str, predicate: typing.Optional[typing.Callable[..., bool]] = None, *, timeout: typing.Optional[float] = None, ) -> AsyncEventContextManager[typing.Any]: ... def expect_event( self, event: str, predicate: typing.Optional[typing.Callable] = None, *, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> AsyncEventContextManager: """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 async with context.expect_event(\"page\") as event_info: await page.get_by_role(\"button\").click() page = await 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 AsyncEventContextManager( 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, ) -> AsyncEventContextManager["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 AsyncEventContextManager( self._impl_obj.expect_page( predicate=self._wrap_handler(predicate), timeout=to_milliseconds(timeout), ).future ) async def expose_binding( self, name: str, callback: typing.Callable ) -> "AsyncContextManager": """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 import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): webkit = playwright.webkit browser = await webkit.launch(headless=False) context = await browser.new_context() await context.expose_binding(\"pageURL\", lambda source: source[\"page\"].url) page = await context.new_page() await page.set_content(\"\"\"
\"\"\") await page.get_by_role(\"button\").click() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` 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 ------- AsyncContextManager """ return mapping.from_impl( await self._impl_obj.expose_binding( name=name, callback=self._wrap_handler(callback) ) ) async def expose_function( self, name: str, callback: typing.Callable ) -> "AsyncContextManager": """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 asyncio import hashlib from playwright.async_api import async_playwright, Playwright def sha256(text: str) -> str: m = hashlib.sha256() m.update(bytes(text, \"utf8\")) return m.hexdigest() async def run(playwright: Playwright): webkit = playwright.webkit browser = await webkit.launch(headless=False) context = await browser.new_context() await context.expose_function(\"sha256\", sha256) page = await context.new_page() await page.set_content(\"\"\"
\"\"\") await page.get_by_role(\"button\").click() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` 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 ------- AsyncContextManager """ return mapping.from_impl( await self._impl_obj.expose_function( name=name, callback=self._wrap_handler(callback) ) ) async 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". """ await 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()) async 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( await self._impl_obj.new_cdp_session(page=mapping.to_impl(page)) ) async def new_page(self) -> "Page": """BrowserContext.new_page Creates a new page in the browser context. Returns ------- Page """ return mapping.from_impl(await self._impl_obj.new_page()) @typing.overload def on( self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"], ) -> None: """ This event is not emitted.""" @typing.overload def on( self, event: Literal["close"], f: typing.Callable[ ["BrowserContext"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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 async def print_args(msg): values = [] for arg in msg.args: values.append(await arg.json_value()) print(values) context.on(\"console\", print_args) await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\") ```""" @typing.overload def on( self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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 async with context.expect_page() as page_info: await page.get_by_text(\"open new page\").click(), page = await page_info.value print(await page.evaluate(\"location.href\")) ``` **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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().on(event=event, f=f) @typing.overload def once( self, event: Literal["backgroundpage"], f: typing.Callable[["Page"], "typing.Union[typing.Awaitable[None], None]"], ) -> None: """ This event is not emitted.""" @typing.overload def once( self, event: Literal["close"], f: typing.Callable[ ["BrowserContext"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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 async def print_args(msg): values = [] for arg in msg.args: values.append(await arg.json_value()) print(values) context.on(\"console\", print_args) await page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\") ```""" @typing.overload def once( self, event: Literal["dialog"], f: typing.Callable[["Dialog"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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 async with context.expect_page() as page_info: await page.get_by_text(\"open new page\").click(), page = await page_info.value print(await page.evaluate(\"location.href\")) ``` **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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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"], "typing.Union[typing.Awaitable[None], 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[..., typing.Union[typing.Awaitable[None], 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) async 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, ) -> "AsyncContextManager": """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 = await browser.new_context() page = await context.new_page() await context.route(\"**/*.{png,jpg,jpeg}\", lambda route: route.abort()) await page.goto(\"https://example.com\") await browser.close() ``` or the same snippet using a regex pattern instead: ```py context = await browser.new_context() page = await context.new_page() await context.route(re.compile(r\"(\\.png$)|(\\.jpg$)\"), lambda route: route.abort()) page = await context.new_page() await page.goto(\"https://example.com\") await browser.close() ``` 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 async def handle_route(route: Route): if (\"my-string\" in route.request.post_data): await route.fulfill(body=\"mocked-data\") else: await route.continue_() await context.route(\"/api/**\", handle_route) ``` Page 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 ------- AsyncContextManager """ return mapping.from_impl( await self._impl_obj.route( url=self._wrap_handler(url), handler=self._wrap_handler(handler), times=times, ) ) async 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. """ await self._impl_obj.route_from_har( har=har, notFound=not_found, update=update, updateContent=update_content, updateMode=update_mode, url=url, ) async 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) async def handler(ws: WebSocketRoute): ws.route_send(lambda message: message_handler(ws, message)) await ws.connect() await 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. """ await 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)) async 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. """ await self._impl_obj.set_extra_http_headers(headers=mapping.to_impl(headers)) async 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 await 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] """ await self._impl_obj.set_geolocation(geolocation=geolocation) async 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. """ await self._impl_obj.set_offline(offline=offline) async 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. await 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()`. """ await self._impl_obj.set_storage_state(storageState=storage_state) async 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( await 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) async 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()`. """ await self._impl_obj.unroute( url=self._wrap_handler(url), handler=self._wrap_handler(handler) ) async 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 """ await self._impl_obj.unroute_all(behavior=behavior) @typing.overload async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async 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 async def wait_for_event( self, event: str, predicate: typing.Optional[typing.Callable[..., bool]] = None, *, timeout: typing.Optional[float] = None, ) -> typing.Any: ... async 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( await self._impl_obj.wait_for_event( event=event, predicate=self._wrap_handler(predicate), timeout=to_milliseconds(timeout), ) ) mapping.register(BrowserContextImpl, BrowserContext) class BrowserType(AsyncBase): _impl_obj: BrowserTypeImpl async 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. `` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`. Some common examples: 1. `"*"` to expose all network. 1. `""` to expose localhost network. 1. `"*.test.internal-domain,*.staging.internal-domain,"` to expose test/staging deployments and localhost. headers : Union[Dict[str, str], None] Additional HTTP headers to be sent with web socket connect request. Optional. slow_mo : Union[float, None] Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0. timeout : Union[float, None] Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout). Returns ------- Browser """ return mapping.from_impl( await self._impl_obj.connect( endpoint=endpoint, exposeNetwork=expose_network, headers=mapping.to_impl(headers), slowMo=slow_mo, timeout=to_milliseconds(timeout), ) ) async def connect_over_cdp( self, endpoint_url: str, *, artifacts_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, headers: typing.Optional[typing.Dict[str, str]] = None, is_local: typing.Optional[bool] = None, no_defaults: typing.Optional[bool] = None, slow_mo: typing.Optional[float] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> "Browser": """BrowserType.connect_over_cdp This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol. The default browser context is accessible via `browser.contexts`. **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers. **NOTE** This connection is significantly lower fidelity than the Playwright protocol connection via `browser_type.connect()`. If you are experiencing issues or attempting to use advanced functionality, you probably want to use `browser_type.connect()`. **NOTE** Playwright maintains a curated list of arguments for launching the browser. If you launch the browser without Playwright and do not pass the exact same arguments, some of Playwright functionality may be broken upon connecting to the browser. **Usage** ```py browser = await playwright.chromium.connect_over_cdp(\"http://localhost:9222\") default_context = browser.contexts[0] page = default_context.pages[0] ``` Parameters ---------- endpoint_url : str A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`. artifacts_dir : Union[pathlib.Path, str, None] If specified, browser artifacts (such as traces and downloads) are saved into this directory. headers : Union[Dict[str, str], None] Additional HTTP headers to be sent with connect request. Optional. is_local : Union[bool, None] Tells Playwright that it runs on the same host as the CDP server. It will enable certain optimizations that rely upon the file system being the same between Playwright and the Browser. no_defaults : Union[bool, None] When true, Playwright will not apply its default overrides to the existing default browser context. Specifically, `accept_downloads` is left at the browser's setting, focus emulation is not enabled, and media emulation options (such as `color_scheme`, `reduced_motion`, `forced_colors`, and `contrast`) are not applied. Useful when attaching to a user's daily-driver browser where these overrides would interfere with existing browser state. New contexts created via `browser.new_context()` are not affected. Defaults to `false`. slow_mo : Union[float, None] Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0. timeout : Union[float, None] Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. Returns ------- Browser """ return mapping.from_impl( await self._impl_obj.connect_over_cdp( endpointURL=endpoint_url, artifactsDir=artifacts_dir, headers=mapping.to_impl(headers), isLocal=is_local, noDefaults=no_defaults, slowMo=slow_mo, timeout=to_milliseconds(timeout), ) ) @property def executable_path(self) -> str: """BrowserType.executable_path A path where Playwright expects to find a bundled browser executable. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.executable_path) async def launch( self, *, args: typing.Optional[typing.Sequence[str]] = None, artifacts_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, channel: typing.Optional[str] = None, chromium_sandbox: typing.Optional[bool] = None, downloads_path: typing.Optional[typing.Union[str, pathlib.Path]] = None, env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None, executable_path: typing.Optional[typing.Union[str, pathlib.Path]] = None, firefox_user_prefs: typing.Optional[ typing.Dict[str, typing.Union[str, float, bool]] ] = None, handle_sighup: typing.Optional[bool] = None, handle_sigint: typing.Optional[bool] = None, handle_sigterm: typing.Optional[bool] = None, headless: typing.Optional[bool] = None, ignore_default_args: typing.Optional[ typing.Union[bool, typing.Sequence[str]] ] = None, proxy: typing.Optional[ProxySettings] = None, slow_mo: typing.Optional[float] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, traces_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, ) -> "Browser": """BrowserType.launch Returns the browser instance. **Usage** You can use `ignore_default_args` to filter out `--mute-audio` from default arguments: ```py browser = await playwright.chromium.launch( # or \"firefox\" or \"webkit\". ignore_default_args=[\"--mute-audio\"] ) ``` > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use `executable_path` option with extreme caution. > > If Google Chrome (rather than Chromium) is preferred, a [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested. > > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs for video playback. See [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for other differences between Chromium and Chrome. [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md) describes some differences for Linux users. Parameters ---------- args : Union[Sequence[str], None] **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality. Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](https://peter.sh/experiments/chromium-command-line-switches/). artifacts_dir : Union[pathlib.Path, str, None] If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser closes. channel : Union[str, None] Browser distribution channel. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode). Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge). chromium_sandbox : Union[bool, None] Enable Chromium sandboxing. Defaults to `false`. downloads_path : Union[pathlib.Path, str, None] If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed. env : Union[Dict[str, Union[bool, float, str]], None] Specify environment variables that will be visible to the browser. Defaults to `process.env`. executable_path : Union[pathlib.Path, str, None] Path to a browser executable to run instead of the bundled one. If `executable_path` is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None] Firefox user preferences. Learn more about the Firefox user preferences at [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox). You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable. handle_sighup : Union[bool, None] Close the browser process on SIGHUP. Defaults to `true`. handle_sigint : Union[bool, None] Close the browser process on Ctrl-C. Defaults to `true`. handle_sigterm : Union[bool, None] Close the browser process on SIGTERM. Defaults to `true`. headless : Union[bool, None] Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`. ignore_default_args : Union[Sequence[str], bool, None] If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`. proxy : Union[{server: str, bypass: Union[str, None], username: Union[str, None], password: Union[str, None]}, None] Network proxy settings. slow_mo : Union[float, None] Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. timeout : Union[float, None] Maximum time in milliseconds to wait for the browser instance to start. Defaults to `180000` (3 minutes). Pass `0` to disable timeout. traces_dir : Union[pathlib.Path, str, None] If specified, traces are saved into this directory. Returns ------- Browser """ return mapping.from_impl( await self._impl_obj.launch( args=mapping.to_impl(args), artifactsDir=artifacts_dir, channel=channel, chromiumSandbox=chromium_sandbox, downloadsPath=downloads_path, env=mapping.to_impl(env), executablePath=executable_path, firefoxUserPrefs=mapping.to_impl(firefox_user_prefs), handleSIGHUP=handle_sighup, handleSIGINT=handle_sigint, handleSIGTERM=handle_sigterm, headless=headless, ignoreDefaultArgs=mapping.to_impl(ignore_default_args), proxy=proxy, slowMo=slow_mo, timeout=to_milliseconds(timeout), tracesDir=traces_dir, ) ) async def launch_persistent_context( self, user_data_dir: typing.Union[str, pathlib.Path], *, accept_downloads: typing.Optional[bool] = None, args: typing.Optional[typing.Sequence[str]] = None, artifacts_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, base_url: typing.Optional[str] = None, bypass_csp: typing.Optional[bool] = None, channel: typing.Optional[str] = None, chromium_sandbox: 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, device_scale_factor: typing.Optional[float] = None, downloads_path: typing.Optional[typing.Union[str, pathlib.Path]] = None, env: typing.Optional[typing.Dict[str, typing.Union[str, float, bool]]] = None, executable_path: typing.Optional[typing.Union[str, pathlib.Path]] = None, extra_http_headers: typing.Optional[typing.Dict[str, str]] = None, firefox_user_prefs: typing.Optional[ typing.Dict[str, typing.Union[str, float, bool]] ] = None, forced_colors: typing.Optional[Literal["active", "none", "null"]] = None, geolocation: typing.Optional[Geolocation] = None, handle_sighup: typing.Optional[bool] = None, handle_sigint: typing.Optional[bool] = None, handle_sigterm: typing.Optional[bool] = None, has_touch: typing.Optional[bool] = None, headless: typing.Optional[bool] = None, http_credentials: typing.Optional[ typing.Union[HttpCredentials, typing.Sequence[HttpCredentials]] ] = None, ignore_default_args: typing.Optional[ typing.Union[bool, typing.Sequence[str]] ] = 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, slow_mo: typing.Optional[float] = None, strict_selectors: typing.Optional[bool] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, timezone_id: typing.Optional[str] = None, traces_dir: typing.Optional[typing.Union[str, pathlib.Path]] = None, user_agent: typing.Optional[str] = None, viewport: typing.Optional[ViewportSize] = None, ) -> "BrowserContext": """BrowserType.launch_persistent_context Returns the persistent browser context instance. Launches browser that uses persistent storage located at `user_data_dir` and returns the only context. Closing this context will automatically close the browser. Parameters ---------- user_data_dir : Union[pathlib.Path, str] Path to a User Data Directory, which stores browser session data like cookies and local storage. Pass an empty string to create a temporary directory. More details for [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and [Firefox](https://wiki.mozilla.org/Firefox/CommandLineOptions#User_profile). Chromium's user data directory is the **parent** directory of the "Profile Path" seen at `chrome://version`. Note that browsers do not allow launching multiple instances with the same User Data Directory. **NOTE** Chromium/Chrome: Due to recent Chrome policy changes, automating the default Chrome user profile is not supported. Pointing `userDataDir` to Chrome's main "User Data" directory (the profile used for your regular browsing) may result in pages not loading or the browser exiting. Create and use a separate directory (for example, an empty folder) as your automation profile instead. See https://developer.chrome.com/blog/remote-debugging-port for details. accept_downloads : Union[bool, None] Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted. args : Union[Sequence[str], None] **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality. Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](https://peter.sh/experiments/chromium-command-line-switches/). artifacts_dir : Union[pathlib.Path, str, None] If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser closes. 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`. channel : Union[str, None] Browser distribution channel. Use "chromium" to [opt in to new headless mode](../browsers.md#chromium-new-headless-mode). Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded [Google Chrome and Microsoft Edge](../browsers.md#google-chrome--microsoft-edge). chromium_sandbox : Union[bool, None] Enable Chromium sandboxing. 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). downloads_path : Union[pathlib.Path, str, None] If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed. env : Union[Dict[str, Union[bool, float, str]], None] Specify environment variables that will be visible to the browser. Defaults to `process.env`. executable_path : Union[pathlib.Path, str, None] Path to a browser executable to run instead of the bundled one. If `executable_path` is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk. extra_http_headers : Union[Dict[str, str], None] An object containing additional HTTP headers to be sent with every request. Defaults to none. firefox_user_prefs : Union[Dict[str, Union[bool, float, str]], None] Firefox user preferences. Learn more about the Firefox user preferences at [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox). You can also provide a path to a custom [`policies.json` file](https://mozilla.github.io/policy-templates/) via `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable. 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] handle_sighup : Union[bool, None] Close the browser process on SIGHUP. Defaults to `true`. handle_sigint : Union[bool, None] Close the browser process on Ctrl-C. Defaults to `true`. handle_sigterm : Union[bool, None] Close the browser process on SIGTERM. Defaults to `true`. has_touch : Union[bool, None] Specifies if viewport supports touch events. Defaults to false. Learn more about [mobile emulation](../emulation.md#devices). headless : Union[bool, None] Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://hacks.mozilla.org/2017/12/using-headless-mode-in-firefox/). Defaults to `true`. 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_default_args : Union[Sequence[str], bool, None] If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`. 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. 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. slow_mo : Union[float, None] Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. 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. timeout : Union[float, None] Maximum time in milliseconds to wait for the browser instance to start. Defaults to `180000` (3 minutes). Pass `0` to disable timeout. 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. traces_dir : Union[pathlib.Path, str, None] If specified, traces are saved into this directory. 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( await self._impl_obj.launch_persistent_context( userDataDir=user_data_dir, acceptDownloads=accept_downloads, args=mapping.to_impl(args), artifactsDir=artifacts_dir, baseURL=base_url, bypassCSP=bypass_csp, channel=channel, chromiumSandbox=chromium_sandbox, clientCertificates=mapping.to_impl(client_certificates), colorScheme=color_scheme, contrast=contrast, deviceScaleFactor=device_scale_factor, downloadsPath=downloads_path, env=mapping.to_impl(env), executablePath=executable_path, extraHTTPHeaders=mapping.to_impl(extra_http_headers), firefoxUserPrefs=mapping.to_impl(firefox_user_prefs), forcedColors=forced_colors, geolocation=geolocation, handleSIGHUP=handle_sighup, handleSIGINT=handle_sigint, handleSIGTERM=handle_sigterm, hasTouch=has_touch, headless=headless, httpCredentials=mapping.to_impl(http_credentials), ignoreDefaultArgs=mapping.to_impl(ignore_default_args), 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, slowMo=slow_mo, strictSelectors=strict_selectors, timeout=to_milliseconds(timeout), timezoneId=timezone_id, tracesDir=traces_dir, userAgent=user_agent, viewport=viewport, ) ) @property def name(self) -> str: """BrowserType.name Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.name) mapping.register(BrowserTypeImpl, BrowserType) class CDPSession(AsyncBase): _impl_obj: CDPSessionImpl async def detach(self) -> None: """CDPSession.detach Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used to send messages. """ await self._impl_obj.detach() @typing.overload def on( self, event: Literal["close"], f: typing.Callable[ ["CDPSession"], "typing.Union[typing.Awaitable[None], None]" ], ) -> None: """ Emitted when the session is closed, either because the target was closed or `session.detach()` was called. """ @typing.overload def on( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: ... def on( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().on(event=event, f=f) @typing.overload def once( self, event: Literal["close"], f: typing.Callable[ ["CDPSession"], "typing.Union[typing.Awaitable[None], None]" ], ) -> None: """ Emitted when the session is closed, either because the target was closed or `session.detach()` was called. """ @typing.overload def once( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: ... def once( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().once(event=event, f=f) async def send( self, method: str, params: typing.Optional[typing.Dict] = None ) -> typing.Dict: """CDPSession.send Parameters ---------- method : str Protocol method name. params : Union[Dict, None] Optional method parameters. Returns ------- Dict """ return mapping.from_maybe_impl( await self._impl_obj.send(method=method, params=mapping.to_impl(params)) ) mapping.register(CDPSessionImpl, CDPSession) class Clock(AsyncBase): _impl_obj: ClockImpl async def fast_forward(self, ticks: typing.Union[int, str]) -> None: """Clock.fast_forward Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it later, after given time. **Usage** ```py await page.clock.fast_forward(1000) await page.clock.fast_forward(\"30:00\") ``` Parameters ---------- ticks : Union[int, str] Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds. """ await self._impl_obj.fast_forward(ticks=ticks) async def install( self, *, time: typing.Optional[typing.Union[float, str, datetime.datetime]] = None, ) -> None: """Clock.install Install fake implementations for the following time-related functions: - `Date` - `Temporal.Now` - `setTimeout` - `clearTimeout` - `setInterval` - `clearInterval` - `requestAnimationFrame` - `cancelAnimationFrame` - `requestIdleCallback` - `cancelIdleCallback` - `performance` Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers, and control the behavior of time-dependent functions. See `clock.run_for()` and `clock.fast_forward()` for more information. Parameters ---------- time : Union[datetime.datetime, float, str, None] Time to initialize with, current system time by default. Numeric values are Unix time in seconds. """ await self._impl_obj.install(time=time) async def pause_at(self, time: typing.Union[float, str, datetime.datetime]) -> None: """Clock.pause_at Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired unless `clock.run_for()`, `clock.fast_forward()`, `clock.pause_at()` or `clock.resume()` is called. Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it at the specified time and pausing. **Usage** ```py await page.clock.pause_at(datetime.datetime(2020, 2, 2)) await page.clock.pause_at(\"2020-02-02\") ``` For best results, install the clock before navigating the page and set it to a time slightly before the intended test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck. Once the page has fully loaded, you can safely use `clock.pause_at()` to pause the clock. ```py # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. await page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0)) await page.goto(\"http://localhost:3333\") await page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0)) ``` Parameters ---------- time : Union[datetime.datetime, float, str] Time to pause at. Numeric values are Unix time in seconds. """ await self._impl_obj.pause_at(time=time) async def resume(self) -> None: """Clock.resume Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual. """ await self._impl_obj.resume() async def run_for(self, ticks: typing.Union[int, str]) -> None: """Clock.run_for Advance the clock, firing all the time-related callbacks. **Usage** ```py await page.clock.run_for(1000); await page.clock.run_for(\"30:00\") ``` Parameters ---------- ticks : Union[int, str] Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds. """ await self._impl_obj.run_for(ticks=ticks) async def set_fixed_time( self, time: typing.Union[float, str, datetime.datetime] ) -> None: """Clock.set_fixed_time Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running. Use this method for simple scenarios where you only need to test with a predefined time. For more advanced scenarios, use `clock.install()` instead. Read docs on [clock emulation](https://playwright.dev/python/docs/clock) to learn more. **Usage** ```py await page.clock.set_fixed_time(datetime.datetime.now()) await page.clock.set_fixed_time(datetime.datetime(2020, 2, 2)) await page.clock.set_fixed_time(\"2020-02-02\") ``` Parameters ---------- time : Union[datetime.datetime, float, str] Time to be set. Numeric values are Unix time in seconds. """ await self._impl_obj.set_fixed_time(time=time) async def set_system_time( self, time: typing.Union[float, str, datetime.datetime] ) -> None: """Clock.set_system_time Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for example switching from summer to winter time, or changing time zones. **Usage** ```py await page.clock.set_system_time(datetime.datetime.now()) await page.clock.set_system_time(datetime.datetime(2020, 2, 2)) await page.clock.set_system_time(\"2020-02-02\") ``` Parameters ---------- time : Union[datetime.datetime, float, str] Time to be set. Numeric values are Unix time in seconds. """ await self._impl_obj.set_system_time(time=time) mapping.register(ClockImpl, Clock) class ConsoleMessage(AsyncBase): _impl_obj: ConsoleMessageImpl @property def args(self) -> typing.List["JSHandle"]: """ConsoleMessage.args List of arguments passed to a `console` function call. See also `page.on('console')`. Returns ------- List[JSHandle] """ return mapping.from_impl_list(self._impl_obj.args) @property def location(self) -> SourceLocation: """ConsoleMessage.location Returns ------- {url: str, line: int, column: int, lineNumber: int, columnNumber: int} """ return mapping.from_impl(self._impl_obj.location) @property def page(self) -> typing.Optional["Page"]: """ConsoleMessage.page The page that produced this console message, if any. Returns ------- Union[Page, None] """ return mapping.from_impl_nullable(self._impl_obj.page) @property def text(self) -> str: """ConsoleMessage.text The text of the console message. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.text) @property def timestamp(self) -> float: """ConsoleMessage.timestamp The timestamp of the console message in milliseconds since the Unix epoch. Returns ------- float """ return mapping.from_maybe_impl(self._impl_obj.timestamp) @property def type( self, ) -> Literal[ "assert", "clear", "count", "debug", "dir", "dirxml", "endGroup", "error", "info", "log", "profile", "profileEnd", "startGroup", "startGroupCollapsed", "table", "time", "timeEnd", "trace", "warning", ]: """ConsoleMessage.type Returns ------- Union["assert", "clear", "count", "debug", "dir", "dirxml", "endGroup", "error", "info", "log", "profile", "profileEnd", "startGroup", "startGroupCollapsed", "table", "time", "timeEnd", "trace", "warning"] """ return mapping.from_maybe_impl(self._impl_obj.type) @property def worker(self) -> typing.Optional["Worker"]: """ConsoleMessage.worker The web worker or service worker that produced this console message, if any. Note that console messages from web workers also have non-null `console_message.page`. Returns ------- Union[Worker, None] """ return mapping.from_impl_nullable(self._impl_obj.worker) mapping.register(ConsoleMessageImpl, ConsoleMessage) class Credentials(AsyncBase): _impl_obj: CredentialsImpl async def create( self, rp_id: str, *, id: typing.Optional[str] = None, private_key: typing.Optional[str] = None, public_key: typing.Optional[str] = None, sign_count: typing.Optional[int] = None, user_handle: typing.Optional[str] = None, ) -> VirtualCredential: """Credentials.create Seeds a virtual WebAuthn credential and returns it. With only `rp_id`, generates a fresh **ECDSA P-256** keypair, credential id and user handle. The seeded credential is discoverable (resident), so the page can resolve it from both username-then-passkey and usernameless passkey flows. The returned object carries the private and public keys, so it can be persisted to disk and re-seeded in a later test. To **import a known credential**, supply all four of `id`, `user_handle`, `private_key` and `public_key` together. Pass `sign_count` as well to continue from the signature counter the relying party has already seen. Call `credentials.install()` before navigating to a page that uses WebAuthn. Parameters ---------- rp_id : str Relying party id (typically the site's effective domain). id : Union[str, None] Base64url-encoded credential id. Auto-generated if omitted. private_key : Union[str, None] Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted. public_key : Union[str, None] Base64url-encoded SPKI (DER) public key. Auto-generated if omitted. sign_count : Union[int, None] Initial value of the [signature counter](https://www.w3.org/TR/webauthn-2/#signature-counter). The counter is incremented by one on every successful `navigator.credentials.get()` assertion, so the first assertion reports `signCount + 1`. Defaults to `0`. user_handle : Union[str, None] Base64url-encoded user handle. Auto-generated if omitted. Returns ------- {id: str, rpId: str, userHandle: str, privateKey: str, publicKey: str, signCount: int} """ return mapping.from_impl( await self._impl_obj.create( rpId=rp_id, id=id, privateKey=private_key, publicKey=public_key, signCount=sign_count, userHandle=user_handle, ) ) async def delete(self, id: str) -> None: """Credentials.delete Removes a credential from the authenticator by its id. Works for any credential currently held — both those seeded with `credentials.create()` and those the page registered itself by calling `navigator.credentials.create()`. Parameters ---------- id : str Base64url-encoded credential id. """ await self._impl_obj.delete(id=id) async def get( self, *, id: typing.Optional[str] = None, rp_id: typing.Optional[str] = None ) -> typing.List[VirtualCredential]: """Credentials.get Returns every credential currently held by the authenticator, optionally filtered by `rp_id` or `id`. This includes both credentials seeded with `credentials.create()` and credentials the page registered itself by calling `navigator.credentials.create()`. Each returned credential includes its private and public keys and the current signature counter, so a passkey the app just registered can be saved and re-seeded into a later test with `credentials.create()` — see the second example in the class overview. Parameters ---------- id : Union[str, None] Only return the credential with this base64url-encoded id. rp_id : Union[str, None] Only return credentials for this relying party id. Returns ------- List[{id: str, rpId: str, userHandle: str, privateKey: str, publicKey: str, signCount: int}] """ return mapping.from_impl_list(await self._impl_obj.get(id=id, rpId=rp_id)) async def install(self) -> None: """Credentials.install Installs the virtual WebAuthn authenticator into the context, overriding `navigator.credentials.create()` and `navigator.credentials.get()` in all current and future pages. Call this before the page first touches `navigator.credentials`. Required: until `credentials.install()` is called, no interception is in place and the page sees the platform's native (or absent) WebAuthn behaviour. Seeding credentials with `credentials.create()` without installing populates the authenticator, but the page will never see those credentials. """ await self._impl_obj.install() mapping.register(CredentialsImpl, Credentials) class Debugger(AsyncBase): _impl_obj: DebuggerImpl async def next(self) -> None: """Debugger.next Resumes script execution and pauses again before the next action. Throws if the debugger is not paused. """ await self._impl_obj.next() @typing.overload def on( self, event: Literal["pausedstatechanged"], f: typing.Callable[["None"], "typing.Union[typing.Awaitable[None], None]"], ) -> None: """ Emitted when the debugger pauses or resumes.""" @typing.overload def on( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: ... def on( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().on(event=event, f=f) @typing.overload def once( self, event: Literal["pausedstatechanged"], f: typing.Callable[["None"], "typing.Union[typing.Awaitable[None], None]"], ) -> None: """ Emitted when the debugger pauses or resumes.""" @typing.overload def once( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: ... def once( self, event: str, f: typing.Callable[..., typing.Union[typing.Awaitable[None], None]], ) -> None: return super().once(event=event, f=f) @property def paused_details(self) -> typing.Optional[DebuggerPausedDetails]: """Debugger.paused_details Returns details about the currently paused call. Returns `null` if the debugger is not paused. Returns ------- Union[{location: {file: str, line: Union[int, None], column: Union[int, None]}, title: str}, None] """ return mapping.from_impl_nullable(self._impl_obj.paused_details) async def request_pause(self) -> None: """Debugger.request_pause Configures the debugger to pause before the next action is executed. Throws if the debugger is already paused. Use `debugger.next()` or `debugger.run_to()` to step while paused. Note that `page.pause()` is equivalent to a \"debugger\" statement — it pauses execution at the call site immediately. On the contrary, `debugger.request_pause()` is equivalent to \"pause on next statement\" — it configures the debugger to pause before the next action is executed. """ await self._impl_obj.request_pause() async def resume(self) -> None: """Debugger.resume Resumes script execution. Throws if the debugger is not paused. """ await self._impl_obj.resume() async def run_to(self, location: DebuggerLocation) -> None: """Debugger.run_to Resumes script execution and pauses when an action originates from the given source location. Throws if the debugger is not paused. Parameters ---------- location : {file: str, line: Union[int, None], column: Union[int, None]} The source location to pause at. """ await self._impl_obj.run_to(location=location) mapping.register(DebuggerImpl, Debugger) class Dialog(AsyncBase): _impl_obj: DialogImpl async def accept(self, prompt_text: typing.Optional[str] = None) -> None: """Dialog.accept Returns when the dialog has been accepted. Parameters ---------- prompt_text : Union[str, None] A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional. """ await self._impl_obj.accept(promptText=prompt_text) @property def default_value(self) -> str: """Dialog.default_value If dialog is prompt, returns default prompt value. Otherwise, returns empty string. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.default_value) async def dismiss(self) -> None: """Dialog.dismiss Returns when the dialog has been dismissed. """ await self._impl_obj.dismiss() @property def message(self) -> str: """Dialog.message A message displayed in the dialog. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.message) @property def page(self) -> typing.Optional["Page"]: """Dialog.page The page that initiated this dialog, if available. Returns ------- Union[Page, None] """ return mapping.from_impl_nullable(self._impl_obj.page) @property def type(self) -> str: """Dialog.type Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.type) mapping.register(DialogImpl, Dialog) class Disposable(AsyncContextManager): _impl_obj: DisposableImpl async def close(self) -> None: await self._impl_obj.close() async def dispose(self) -> None: """Disposable.dispose Removes the associated resource. For example, removes the init script installed via `page.add_init_script()` or `browser_context.add_init_script()`. """ await self._impl_obj.dispose() mapping.register(DisposableImpl, Disposable) class Download(AsyncBase): _impl_obj: DownloadImpl async def cancel(self) -> None: """Download.cancel Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations, `download.failure()` would resolve to `'canceled'`. """ await self._impl_obj.cancel() async def delete(self) -> None: """Download.delete Deletes the downloaded file. Will wait for the download to finish if necessary. """ await self._impl_obj.delete() async def failure(self) -> typing.Optional[str]: """Download.failure Returns download error if any. Will wait for the download to finish if necessary. Returns ------- Union[str, None] """ return mapping.from_maybe_impl(await self._impl_obj.failure()) @property def page(self) -> "Page": """Download.page Get the page that the download belongs to. Returns ------- Page """ return mapping.from_impl(self._impl_obj.page) async def path(self) -> pathlib.Path: """Download.path Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method will wait for the download to finish if necessary. The method throws when connected remotely. Note that the download's file name is a random GUID, use `download.suggested_filename` to get suggested file name. Returns ------- pathlib.Path """ return mapping.from_maybe_impl(await self._impl_obj.path()) async def save_as(self, path: typing.Union[str, pathlib.Path]) -> None: """Download.save_as Copy the download to a user-specified path. It is safe to call this method while the download is still in progress. Will wait for the download to finish if necessary. **Usage** ```py await download.save_as(\"/path/to/save/at/\" + download.suggested_filename) ``` Parameters ---------- path : Union[pathlib.Path, str] Path where the download should be copied. """ await self._impl_obj.save_as(path=path) @property def suggested_filename(self) -> str: """Download.suggested_filename Returns suggested filename for this download. It is typically computed by the browser from the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different browsers can use different logic for computing it. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.suggested_filename) @property def url(self) -> str: """Download.url Returns downloaded url. Returns ------- str """ return mapping.from_maybe_impl(self._impl_obj.url) mapping.register(DownloadImpl, Download) class JSHandle(AsyncBase): _impl_obj: JSHandleImpl def as_element(self) -> typing.Optional["ElementHandle"]: """JSHandle.as_element Returns either `null` or the object handle itself, if the object handle is an instance of `ElementHandle`. Returns ------- Union[ElementHandle, None] """ return mapping.from_impl_nullable(self._impl_obj.as_element()) async def dispose(self) -> None: """JSHandle.dispose The `jsHandle.dispose` method stops referencing the element handle. """ await self._impl_obj.dispose() async def evaluate( self, expression: str, arg: typing.Optional[typing.Any] = None ) -> typing.Any: """JSHandle.evaluate Returns the return value of `expression`. This method passes this handle as the first argument to `expression`. If `expression` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value. **Usage** ```py tweet_handle = await page.query_selector(\".tweet .retweets\") assert await tweet_handle.evaluate(\"node => node.innerText\") == \"10 retweets\" ``` Parameters ---------- expression : str JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked. arg : Union[Any, None] Optional argument to pass to `expression`. Returns ------- Any """ return mapping.from_maybe_impl( await self._impl_obj.evaluate( expression=expression, arg=mapping.to_impl(arg) ) ) async def evaluate_handle( self, expression: str, arg: typing.Optional[typing.Any] = None ) -> "JSHandle": """JSHandle.evaluate_handle Returns the return value of `expression` as a `JSHandle`. This method passes this handle as the first argument to `expression`. The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle` returns `JSHandle`. If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would wait for the promise to resolve and return its value. See `page.evaluate_handle()` for more details. Parameters ---------- expression : str JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked. arg : Union[Any, None] Optional argument to pass to `expression`. Returns ------- JSHandle """ return mapping.from_impl( await self._impl_obj.evaluate_handle( expression=expression, arg=mapping.to_impl(arg) ) ) async def get_properties(self) -> typing.Dict[str, "JSHandle"]: """JSHandle.get_properties The method returns a map with **own property names** as keys and JSHandle instances for the property values. **Usage** ```py handle = await page.evaluate_handle(\"({ window, document })\") properties = await handle.get_properties() window_handle = properties.get(\"window\") document_handle = properties.get(\"document\") await handle.dispose() ``` Returns ------- Dict[str, JSHandle] """ return mapping.from_impl_dict(await self._impl_obj.get_properties()) async def get_property(self, property_name: str) -> "JSHandle": """JSHandle.get_property Fetches a single property from the referenced object. Parameters ---------- property_name : str property to get Returns ------- JSHandle """ return mapping.from_impl( await self._impl_obj.get_property(propertyName=property_name) ) async def json_value(self) -> typing.Any: """JSHandle.json_value Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**. **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw an error if the object has circular references. Returns ------- Any """ return mapping.from_maybe_impl(await self._impl_obj.json_value()) mapping.register(JSHandleImpl, JSHandle) class ElementHandle(JSHandle): _impl_obj: ElementHandleImpl async def bounding_box(self) -> typing.Optional[FloatRect]: """ElementHandle.bounding_box This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser window. Scrolling affects the returned bounding box, similarly to [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). That means `x` and/or `y` may be negative. Elements from child frames return the bounding box relative to the main frame, unlike the [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following snippet should click the center of the element. **Usage** ```py box = await element_handle.bounding_box() await page.mouse.click(box[\"x\"] + box[\"width\"] / 2, box[\"y\"] + box[\"height\"] / 2) ``` Returns ------- Union[{x: float, y: float, width: float, height: float}, None] """ return mapping.from_impl_nullable(await self._impl_obj.bounding_box()) async def check( self, *, force: typing.Optional[bool] = None, no_wait_after: typing.Optional[bool] = None, position: typing.Optional[Position] = None, scroll: typing.Optional[Literal["auto", "none"]] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, trial: typing.Optional[bool] = None, ) -> None: """ElementHandle.check This method checks the element by performing the following steps: 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately. 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set. 1. Scroll the element into view if needed. 1. Use `page.mouse` to click in the center of the element. 1. Ensure that the element is now checked. If not, this method throws. If the element is detached from the DOM at any moment during the action, this method throws. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this. Parameters ---------- force : Union[bool, None] Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`. no_wait_after : Union[bool, None] This option has no effect. Deprecated: This option has no effect. position : Union[{x: float, y: float}, None] A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element. scroll : Union["auto", "none", None] Controls whether Playwright scrolls the element into view before performing the action. Defaults to `"auto"`, which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to `"none"`, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This is useful to assert that an element is reachable by the user without additional scrolling. timeout : Union[float, None] Maximum time 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()` or `page.set_default_timeout()` methods. trial : Union[bool, None] When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults to `false`. Useful to wait until the element is ready for the action without performing it. """ await self._impl_obj.check( force=force, noWaitAfter=no_wait_after, position=position, scroll=scroll, timeout=to_milliseconds(timeout), trial=trial, ) async def click( self, *, button: typing.Optional[Literal["left", "middle", "right"]] = None, click_count: typing.Optional[int] = None, delay: typing.Optional[float] = None, force: typing.Optional[bool] = None, modifiers: typing.Optional[ typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]] ] = None, no_wait_after: typing.Optional[bool] = None, position: typing.Optional[Position] = None, scroll: typing.Optional[Literal["auto", "none"]] = None, steps: typing.Optional[int] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, trial: typing.Optional[bool] = None, ) -> None: """ElementHandle.click This method clicks the element by performing the following steps: 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set. 1. Scroll the element into view if needed. 1. Use `page.mouse` to click in the center of the element, or the specified `position`. 1. Wait for initiated navigations to either succeed or fail, unless `no_wait_after` option is set. If the element is detached from the DOM at any moment during the action, this method throws. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this. Parameters ---------- button : Union["left", "middle", "right", None] Defaults to `left`. click_count : Union[int, None] defaults to 1. See [UIEvent.detail]. delay : Union[float, None] Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0. force : Union[bool, None] Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None] Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS. no_wait_after : Union[bool, None] Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`. Deprecated: This option will default to `true` in the future. position : Union[{x: float, y: float}, None] A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element. scroll : Union["auto", "none", None] Controls whether Playwright scrolls the element into view before performing the action. Defaults to `"auto"`, which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to `"none"`, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This is useful to assert that an element is reachable by the user without additional scrolling. steps : Union[int, None] Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location. timeout : Union[float, None] Maximum time 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()` or `page.set_default_timeout()` methods. trial : Union[bool, None] When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults to `false`. Useful to wait until the element is ready for the action without performing it. """ await self._impl_obj.click( button=button, clickCount=click_count, delay=delay, force=force, modifiers=mapping.to_impl(modifiers), noWaitAfter=no_wait_after, position=position, scroll=scroll, steps=steps, timeout=to_milliseconds(timeout), trial=trial, ) async def content_frame(self) -> typing.Optional["Frame"]: """ElementHandle.content_frame Returns the content frame for element handles referencing iframe nodes, or `null` otherwise Returns ------- Union[Frame, None] """ return mapping.from_impl_nullable(await self._impl_obj.content_frame()) async def dblclick( self, *, button: typing.Optional[Literal["left", "middle", "right"]] = None, delay: typing.Optional[float] = None, force: typing.Optional[bool] = None, modifiers: typing.Optional[ typing.Sequence[Literal["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]] ] = None, no_wait_after: typing.Optional[bool] = None, position: typing.Optional[Position] = None, scroll: typing.Optional[Literal["auto", "none"]] = None, steps: typing.Optional[int] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, trial: typing.Optional[bool] = None, ) -> None: """ElementHandle.dblclick This method double clicks the element by performing the following steps: 1. Wait for [actionability](https://playwright.dev/python/docs/actionability) checks on the element, unless `force` option is set. 1. Scroll the element into view if needed. 1. Use `page.mouse` to double click in the center of the element, or the specified `position`. If the element is detached from the DOM at any moment during the action, this method throws. When all steps combined have not finished during the specified `timeout`, this method throws a `TimeoutError`. Passing zero timeout disables this. **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event. Parameters ---------- button : Union["left", "middle", "right", None] Defaults to `left`. delay : Union[float, None] Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0. force : Union[bool, None] Whether to bypass the [actionability](../actionability.md) checks. Defaults to `false`. modifiers : Union[Sequence[Union["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]], None] Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to "Control" on Windows and Linux and to "Meta" on macOS. no_wait_after : Union[bool, None] This option has no effect. Deprecated: This option has no effect. position : Union[{x: float, y: float}, None] A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element. scroll : Union["auto", "none", None] Controls whether Playwright scrolls the element into view before performing the action. Defaults to `"auto"`, which scrolls the element into view when necessary, including scrolling nested scrollable containers. When set to `"none"`, Playwright does not scroll the element and the action fails if the element is not already in the viewport. This is useful to assert that an element is reachable by the user without additional scrolling. steps : Union[int, None] Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location. timeout : Union[float, None] Maximum time 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()` or `page.set_default_timeout()` methods. trial : Union[bool, None] When set, this method only performs the [actionability](../actionability.md) checks and skips the action. Defaults to `false`. Useful to wait until the element is ready for the action without performing it. """ await self._impl_obj.dblclick( button=button, delay=delay, force=force, modifiers=mapping.to_impl(modifiers), noWaitAfter=no_wait_after, position=position, scroll=scroll, steps=steps, timeout=to_milliseconds(timeout), trial=trial, ) async def dispatch_event( self, type: str, event_init: typing.Optional[typing.Dict] = None ) -> None: """ElementHandle.dispatch_event The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element, `click` is dispatched. This is equivalent to calling [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click). **Usage** ```py await element_handle.dispatch_event(\"click\") ``` Under the hood, it creates an instance of an event based on the given `type`, initializes it with `event_init` properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default. Since `event_init` is event-specific, please refer to the events documentation for the lists of initial properties: - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent) - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent) - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent) - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event) - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent) - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent) - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent) - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent) - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent) - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent) You can also specify `JSHandle` as the property value if you want live objects to be passed into the event: ```py # note you can only create data_transfer in chromium and firefox data_transfer = await page.evaluate_handle(\"new DataTransfer()\") await element_handle.dispatch_event(\"#source\", \"dragstart\", {\"dataTransfer\": data_transfer}) ``` Parameters ---------- type : str DOM event type: `"click"`, `"dragstart"`, etc. event_init : Union[Dict, None] Optional event-specific initialization properties. """ await self._impl_obj.dispatch_event( type=type, eventInit=mapping.to_impl(event_init) ) async def eval_on_selector( self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None ) -> typing.Any: """ElementHandle.eval_on_selector Returns the return value of `expression`. The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first argument to `expression`. If no elements match the selector, the method throws an error. If `expression` returns a [Promise], then `element_handle.eval_on_selector()` would wait for the promise to resolve and return its value. **Usage** ```py tweet_handle = await page.query_selector(\".tweet\") assert await tweet_handle.eval_on_selector(\".like\", \"node => node.innerText\") == \"100\" assert await tweet_handle.eval_on_selector(\".retweets\", \"node => node.innerText\") == \"10\" ``` Parameters ---------- selector : str A selector to query for. expression : str JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked. arg : Union[Any, None] Optional argument to pass to `expression`. Returns ------- Any """ return mapping.from_maybe_impl( await self._impl_obj.eval_on_selector( selector=selector, expression=expression, arg=mapping.to_impl(arg) ) ) async def eval_on_selector_all( self, selector: str, expression: str, arg: typing.Optional[typing.Any] = None ) -> typing.Any: """ElementHandle.eval_on_selector_all Returns the return value of `expression`. The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of matched elements as a first argument to `expression`. If `expression` returns a [Promise], then `element_handle.eval_on_selector_all()` would wait for the promise to resolve and return its value. **Usage** ```html
Hello!
Hi!
``` ```py feed_handle = await page.query_selector(\".feed\") assert await feed_handle.eval_on_selector_all(\".tweet\", \"nodes => nodes.map(n => n.innerText)\") == [\"hello!\", \"hi!\"] ``` Parameters ---------- selector : str A selector to query for. expression : str JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked. arg : Union[Any, None] Optional argument to pass to `expression`. Returns ------- Any """ return mapping.from_maybe_impl( await self._impl_obj.eval_on_selector_all( selector=selector, expression=expression, arg=mapping.to_impl(arg) ) ) async def fill( self, value: str, *, force: typing.Optional[bool] = None, no_wait_after: typing.Optional[bool] = None, timeout: typing.Optional[typing.Union[float, datetime.timedelta]] = None, ) -> None: """ElementHandle.fill This method waits for [actionability](https://playwright.dev/python/docs/actionability) checks, focuses the element, fills it and triggers an `input` event after filling. Note that you can pass an empty string to clear the input field. If the target element is not an ``, `