mokr.browser ============ .. py:module:: mokr.browser Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/mokr/browser/browser/index /autoapi/mokr/browser/console/index /autoapi/mokr/browser/context/index /autoapi/mokr/browser/page/index /autoapi/mokr/browser/target/index /autoapi/mokr/browser/viewport/index /autoapi/mokr/browser/worker/index Classes ------- .. autoapisummary:: mokr.browser.Browser mokr.browser.ConsoleMessage mokr.browser.BrowserContext mokr.browser.Page mokr.browser.Target mokr.browser.ViewportManager mokr.browser.WebWorker Package Contents ---------------- .. py:class:: Browser(browser_type: Literal['chrome', 'firefox'], connection: mokr.connection.Connection, context_ids: list[str], ignore_https_errors: bool, default_viewport: dict | None, process: subprocess.Popen | None = None, close_callback: Callable | None = None, proxy_credentials: dict | None = None, default_user_agent: str | None = None, **kwargs: Any) Bases: :py:obj:`pyee.EventEmitter` This class is created upon connect to a browser. It is essentially a container for the individual pages and browser contexts. :param browser_type: The type of browser. :type browser_type: Literal["chrome", "firefox"] :param connection: Websocket connection. :type connection: `mokr.network.Connection` :param context_ids: Browser context identifiers. :type context_ids: list[str] :param ignore_https_errors: Ignore site security errors. :type ignore_https_errors: bool :param default_viewport: Default viewport configuration. :type default_viewport: dict | None :param process: Local browser process, if any. Defaults to None. :type process: Popen | None, optional :param close_callback: Callback to run on close. Defaults to None. :type close_callback: Callable | None, optional :param proxy_credentials: (dict | None, optional): Dictionary with proxy credentials keyed as "username" and "password". Credentials should be for the proxy the browser process is bound to. :param default_user_agent: Default user agent to use on all new pages. :type default_user_agent: str, optional .. py:property:: kind :type: str One of "chrome" or "firefox". .. py:property:: process :type: subprocess.Popen | None The local browser process. If created via `mokr.connect`, will return None. .. py:property:: version :type: str Get browser version (product from browser full version info.) .. py:property:: user_agent :type: str Get the user agent the browser was spawned with or that is set as the default to override with. This can be overidden later again with `mokr.browser.Page.set_user_agent`. .. py:property:: browser_contexts :type: list[mokr.browser.context.BrowserContext] A list of all `mokr.browser.BrowserContext` instances attached to this browser. By default, this will be a single context. .. py:property:: ws_endpoint :type: str The websocket URL that this `Browser`'s `mokr.connection.Connection` object is using. .. py:method:: first_page() -> mokr.browser.page.Page | None :async: Return the first page in the default context's `BrowserContext.pages`. If no pages active, returns None. :returns: First active page in the default context, if any. :rtype: Page | None .. py:method:: ready() -> Browser :async: Enable target discovery in the remote connection. :returns: This `Browser` class. :rtype: Browser .. py:method:: create_incognito_browser_context() -> mokr.browser.context.BrowserContext :async: Create a new browser context. This is akin to spawning an incognito browser window, it will not share cookies or storage with pages in other contexts. To do so, use `Browser.new_page` instead. Example:: browser = await launch().launch() # Navigate and login or perform another storage-accessed action. context = await browser.create_incognito_browser_context() page = await context.first_page() # Navigate to the same site. Session isn't shared! ... :returns: A new `mokr.browser.BrowserContext`. :rtype: BrowserContext .. py:method:: new_page() -> mokr.browser.page.Page :async: Spawn a new page within the default context. :returns: A new `mokr.browser.Page` at "about:blank". :rtype: Page .. py:method:: targets() -> list[mokr.browser.target.Target] A list of all `mokr.browser.Target`s in all contexts attached to this `Browser` object. :returns: All initialised targets within all contexts in this browser. :rtype: list[Target] .. py:method:: pages() -> list[mokr.browser.page.Page] :async: A list of all `mokr.browser.Page`s in all contexts attached to this `Browser` object. :returns: All pages within all contexts in this browser. :rtype: list[Page] .. py:method:: close() -> None :async: Run the `close_callback` given during initialisation. .. py:method:: disconnect() -> None :async: Disconnect the `Browser`'s `Connection` object's websocket connection and fail any `Browser.targets` that haven't finished initialising. .. py:class:: ConsoleMessage(kind: str, text: str, args: list[mokr.execution.JavascriptHandle] = None) Representation of console messages, dispatched on `console` event in `mokr.browser.Page`. :param kind: The type of message. :type kind: str :param text: The message body. :type text: str :param args: Arguments attached to this message. Defaults to None. :type args: list[JavascriptHandle], optional .. py:property:: kind :type: str Return type of this message. .. py:property:: text :type: str Return text representation of the message body. .. py:property:: args :type: list[mokr.execution.JavascriptHandle] Return list of argumentss (JavascriptHandle) of this message. .. py:class:: BrowserContext(browser: mokr.browser.Browser, context_id: str | None) Bases: :py:obj:`pyee.EventEmitter` Browser context within the browser process. Contexts are independent of one another, not sharing storage. Contexts beyond the default context that `mokr.browser.Browser` starts with will be incognito. :param browser: Parent `mokr.browser.Browser` object from which the context was spawned. :type browser: Browser :param context_id: The context identifier (may be None). :type context_id: str | None .. py:property:: incognito :type: bool True if the browser context is incognito, otherwise False. Only default context spawned when the `mokr.browser.Browser` object is spawned is not incognito. .. py:property:: browser :type: mokr.browser.Browser The `mokr.browser.Browser` object this context is attached to. .. py:method:: targets() -> list[mokr.browser.target.Target] A list of all `mokr.browser.Target`s in this context. :returns: All initialised targets within this context. :rtype: list[Target] .. py:method:: pages() -> list[mokr.browser.page.Page] :async: A list of all `mokr.browser.Page`s in this context. :returns: All pages within this context. :rtype: list[Page] .. py:method:: first_page() -> mokr.browser.page.Page :async: Return the first page in `BrowserContext.pages`. If no pages active, returns None. :returns: First active page in this context, if any. :rtype: Page | None .. py:method:: new_page() -> mokr.browser.page.Page :async: Spawn a new page. :returns: A new `mokr.browser.Page` at "about:blank". :rtype: Page .. py:method:: close() -> None :async: Close the context. Can only be done on incognito contexts. :raises BrowserError: Raised if called from the default context. .. py:class:: Page(browser: mokr.browser.Browser, client: mokr.connection.DevtoolsConnection, target: mokr.browser.target.Target, frame_tree: dict, ignore_https_errors: bool, user_agent: str = None, screenshot_task_queue: list = None, proxy_credentials: dict | None = None) Bases: :py:obj:`pyee.EventEmitter` Representative of a single tab within the browser (more specifically, within the browser context). This class is laregly the entry-point for most navigation, execution, or dom-manipulation tasks. Many methods within this class are simply wrappers to bound classes within it. `Page` emits events, often "inherited" from other classes (emitted in series on recieving them from bound classes); these events can be listened on via `Page.on`. Note, however, that certain network events will be bound directly to this `Page`'s `mokr.network.NetworkManager` when passed to `Page.on`. Additionally, `Page.on("request")` will not behaviour as a regular listener, but instead be added to the request interception callback chain. See `Page.on` for more. :param browser: Parent `mokr.browser.Browser`. :type browser: Browser :param client: From parent `mokr.browser.Target`. :type client: DevtoolsConnection :param target: Spawning `mokr.browser.Target`. :type target: Target :param frame_tree: Frame tree structure from remote connection. :type frame_tree: dict :param ignore_https_errors: Ignore site security errors. Inherited from parent `mokr.browser.Browser`. :type ignore_https_errors: bool :param user_agent: User agent for this page. Inherited from parent `mokr.browser.Browser`. :type user_agent: str :param screenshot_task_queue: The screenshot task queue, empty by default. Inherited from parent `mokr.browser.Browser`. :type screenshot_task_queue: list, optional :param proxy_credentials: (dict | None, optional): Dictionary with proxy credentials keyed as "username" and "password". Credentials should be for the proxy the browser process is bound to. Inherited from parent `mokr.browser.Browser`. .. py:method:: create(browser: mokr.browser.Browser, client: mokr.connection.DevtoolsConnection, target: mokr.browser.target.Target, ignore_https_errors: bool, default_viewport: dict | None, screenshot_task_queue: list = None, proxy_credentials: dict | None = None, user_agent_data: dict[str, str] | None = None) -> Page :staticmethod: :async: Async constructor for this class. Necessary to run some asyncronous post-initialisation tasks. :param browser: Parent `mokr.browser.Browser`. :type browser: Browser :param client: From parent `mokr.browser.Target`. :type client: DevtoolsConnection :param target: Spawning `mokr.browser.Target`. :type target: Target :param ignore_https_errors: Ignore site security errors. Inherited from parent `mokr.browser.Browser`. :type ignore_https_errors: bool :param default_viewport: Default viewport configuration. :type default_viewport: dict | None :param screenshot_task_queue: The screenshot task queue, empty by default. Inherited from parent `mokr.browser.Browser`. :type screenshot_task_queue: list, optional :param proxy_credentials: (dict | None, optional): Dictionary with proxy credentials keyed as "username" and "password". Credentials should be for the proxy the browser process is bound to. Inherited from parent `mokr.browser.Browser`. :param user_agent_data: A dictionary containing the user agent and an indicator to whether it was the original or an override. :type user_agent_data: dict[str, str] | None, optional :returns: New `Page` with necessary remote configuration enabled. :rtype: Page .. py:property:: target :type: mokr.browser.target.Target Parent `mokr.browser.Target` this `Page` was spawned from. .. py:property:: browser :type: mokr.browser.Browser Parent `mokr.browser.Browser` this `Page` belongs to. .. py:property:: main_frame :type: mokr.frame.Frame | None This `Page`'s `mokr.frame.FrameManager`'s main `mokr.frame.Frame`. .. py:property:: network_manager :type: mokr.network.NetworkManager | None This `Page`'s `mokr.network.NetworkManager`. .. py:property:: fetch_domain :type: mokr.network.FetchDomain This `Page`'s `mokr.fetch.FetchDomain`. .. py:property:: http_domain :type: mokr.network.HttpDomain This `Page`'s `mokr.network.HttpDomain`. .. py:property:: keyboard :type: mokr.input.Keyboard This `Page`'s `mokr.input.Keyboard`. .. py:property:: mouse :type: mokr.input.Mouse This `Page`'s `mokr.input.Mouse`. .. py:property:: touchscreen :type: mokr.input.Touchscreen This `Page`'s `mokr.input.Touchscreen`. .. py:property:: frames :type: list[mokr.frame.Frame] List of all `mokr.frame.Frames` within this `Page`. .. py:property:: workers :type: list[mokr.browser.worker.WebWorker] List of all `mokr.browser.WebWorker`s within this `Page`. .. py:property:: url :type: str The URL the `Page` is currently at. .. py:property:: viewport :type: dict | None Current viewport configuration, if any. .. py:property:: user_agent :type: str | None The user agent given to override on all requests, if any. .. py:property:: is_closed :type: bool True if the `Page` is still alive, otherwise False. If a parent `mokr.browser.BrowserContext` is closed, all child `Page`s will close, too. .. py:property:: browser_type :type: str One of "chrome" or "firefox". .. py:method:: on(event: str, method: Callable | None) -> None Registers the callable `method` to the event name `event`, if provided. When the target `event` is emitted by this class, the target `method` will be called. Notably, the event "request" does not register a listener. Instead, it adds the method to this `Page`'s `mokr.network.NetworkManager`'s request interception callback chain, which is already registered as a listener on "request" events, if interception is enabled. This callback chain allows multiple manipulations of requests, until the intercepted `mokr.network.Request` is `Request.released`, `.aborted`, or `.fulfilled`. For request interception, methods are executed in reverse order of registration, so newer `Page.on` methods will run first. :param event: Event name to listen for. :type event: str :param method: Method to call when event is emitted. :type method: Callable | None Example:: # Printing worker URL on creation, standard functionality. page.on("workercreated", lambda worker: print(worker.url)) # Adding a handler to the request interception chain. async def intercept(request: Request) -> Request | None: if request.url.endswith("png"): # Request will be killed, interception chain stopped here. await request.abort() elif request.url.endswith("jpg"): # Request will continue in the interception chain. return request else: # Request will be finished, interception chain stopped here. await request.release() # Handlers can be synchronous, too. def note_url(request: Request) -> Request: print(request.url) return request page.on("request", note_url) page.on("request", intercept) .. py:method:: make_http_domain(sync_cookies: Literal['both', 'http', 'page', 'none'] = 'both', **httpx_client_kwargs) -> None Create a `mokr.network.HttpDomain` bound to this page. This method does not ever need to be called directly; accessing `Page.http_domain` will create a new domain with default values. This exists so any optional arguments could be passed to the constructor. Optionally set the cookie sync behaviour by setting `sync_cookies` to: - "both" (default): Sync back and forth. - "http": Sync to the `HttpDomain` from the `Page` only. - "page": Sync to the `Page` from the `HttpDomain` only. - "none": Don't sync at all. :param sync_cookies: Whether to sync cookies between the `HttpDomain` and the parent `Page` before/after each request and response. Defaults to "both". :type sync_cookies: Literal["both", "http", "page", "none"], optional .. py:method:: set_request_interception_enabled(choice: bool) -> None :async: Disable or enabled request interception (enabled by default). See `Page.on` for details on using the request interception callback chain. :param choice: False to disable, True to enable. :type choice: bool .. py:method:: tap(selector: str) -> None :async: Tap the first element that matches `selector`. Wrapper for `Page.main_frame.tap`. This method is a shortcut for running `Page.query_selector` and then running `mokr.execution.ElementHandle.tap` on the resultant ElementHandle. In either case, an element will be scrolled into view if needed, and the center of it clicked with the ElementHandle's bound `Page.touchscreen`. :param selector: Selector to query element by. :type selector: str :raises PageError: Raised if no element is found with given `selector`. .. py:method:: set_offline_mode(choice: bool) -> None :async: Enable or diable offline mode. Disabled by default. Wrapper for `Page.network_manager.set_offline_mode`. :param enabled: False to disable, True to enable. :type enabled: bool .. py:method:: set_default_navigation_timeout(timeout: int) -> None Change the default navigation timeout. This is used by `Page.goto`, `Page.go_back`, `Page.go_forward`, `Page.wait_for_navigation`, `Page.refresh`, and `Page.fetch`, unless overridden. :param timeout: Milliseconds to wait. Use 0 for infinite. :type timeout: int .. py:method:: evaluate_handle(page_function: str, *args: Any) -> mokr.execution.JavascriptHandle :async: Execute a JavaScript function with given arguments. Runs this `Page`'s default `mokr.frame.Frame.evaluate_handle`. :param page_function: JavaScript function to run. :type page_function: str :raises PageError: Raised if the `Page`'s main `mokr.frame.Frame` fails to find its `mokr.browser.ExecutionContext`. :returns: `mokr.execution.JavascriptHandle`. :rtype: JavascriptHandle .. py:method:: query_objects(javascript_handle: mokr.execution.JavascriptHandle) -> mokr.execution.JavascriptHandle :async: Query all objects with the given `mokr.execution.JavascriptHandle`'s `get_property("objectId")`. Wrapper for this `Page.main_frame`'s `mokr.execution.ExecutionContext.query_objects`. :param javascript_handle: A valid (not disposed) `mokr.execution.JavascriptHandle` object. :type javascript_handle: JavascriptHandle :raises PageError: Raised if the `Page`'s main `mokr.frame.Frame` fails to find its `mokr.browser.ExecutionContext`. :raises ElementHandleError: Raised if the given handle is disposed, or does not have an "objectId" remote property (primitive type). :returns: A `mokr.execution.JavascriptHandle` initialised from the remot response. :rtype: JavascriptHandle .. py:method:: query_selector(selector: str) -> mokr.execution.ElementHandle | None :async: Return the first element in the DOM that matches the selector, if any. Wrapper for `Page.main_frame.query_selector`. :param selector: Element selector to locate. :type selector: str :returns: ElementHandle if found or None. :rtype: ElementHandle | None .. py:method:: query_selector_all(selector: str) -> list[mokr.execution.ElementHandle] :async: Return all elements in the DOM that match the selector, if any. Wrapper for `Page.main_frame.query_selector_all`. :param selector: Element selector to locate. :type selector: str :returns: List of ElementHandle if any or empty list. :rtype: list[ElementHandle] .. py:method:: xpath(expression: str) -> list[mokr.execution.ElementHandle] :async: Return all elements in the DOM that match the expression, if any. Wrapper for `Page.main_frame.xpath`. :param expression: XPath expression to evaluate. :type expression: str :returns: List of ElementHandle if any or empty list. :rtype: list[ElementHandle] .. py:method:: cookies() -> list[dict[str, str | int | bool]] :async: Get all cookies accessible to the browser. :returns: List of dictionaries representing each cookie. :rtype: list[dict[str, str | int | bool]] .. py:method:: get_cookies_by_urls(urls: list[str] | None = None) -> list[dict[str, str | int | bool]] :async: Get cookies for the given URLs. If no URLs are given, defaults to a list containing the URLs of the page and all of its frames. :param urls: List of URLs to get cookies for. Defaults to None. :type urls: list[str] | None :returns: List of dictionaries representing each cookie. :rtype: list[dict[str, str | int | bool]] .. py:method:: delete_cookies(cookies: list[dict]) -> None :async: Delete a cookie from this `Page`. :param cookies: A list of dictionaries representing a cookie entry. Each dictionary must at minimum contain a "name". :type cookies: list[dict] .. py:method:: set_cookies(cookies: list[dict]) -> None :async: Set a cookie on this `Page`. :param cookies: A list of dictionaries representing a cookie entry. Each dictionary must at minimum contain a "name" and a "value". :type cookies: list[dict] :raises PageError: Raised if the current page is blank ("about:blank") or is a data URL (starts with "data:"). .. py:method:: embed_javascript(file_content: str = None, file_path: str = None, url: str = None, script_type: str = None) -> mokr.execution.ElementHandle :async: Add script tag to this `Page.main_frame`. Wrapper for `Page.main_frame.embed_javascript`. :param file_content: Encoded file content for script to embed. If not given, must give `file_path` or `url`. Defaults to None. :type file_content: str, optional :param file_path: File path for script to embed. If not given, must give `file_content` or `url`. Defaults to None. :type file_path: str, optional :param url: URL for script to embed. If not given, must give `file_content` or `file_path`. Defaults to None. :type url: str, optional :param script_type: Use "module" to load as JavaScript ES6 module, if not given, defaults to "text/javascript". Defaults to None. :type script_type: str, optional :raises ValueError: Raised if none of `file_content`, `file_path`, or `url` are given. :raises PageError: Raised if error occurs sending embed request to remote connection (from ElementHandleError). :returns: Newly embedded element. :rtype: ElementHandle .. py:method:: embed_style(file_content: str = None, file_path: str = None, url: str = None) -> mokr.execution.ElementHandle :async: Add style tag to this `Page.main_frame`. Wrapper for `Page.main_frame.embed_style`. :param file_content: Encoded file content for style to embed. If not given, must give `file_path` or `url`. Defaults to None. :type file_content: str, optional :param file_path: File path for style to embed. If not given, must give `file_content` or `url`. Defaults to None. :type file_path: str, optional :param url: URL for style to embed. If not given, must give `file_content` or `file_path`. Defaults to None. :type url: str, optional :raises ValueError: Raised if none of `file_content`, `file_path`, or `url` are given. :raises PageError: Raised if error occurs sending embed request to remote connection (from ElementHandleError). :returns: Newly embedded element. :rtype: ElementHandle .. py:method:: expose_function(name: str, method: Callable) -> None :async: Bind a remote JavaScript function "name" to local `method`. This will allow triggering local `method` by calling `window["name"]()` in the browser. :param name: Remote JavaScript function name. :type name: str :param method: Local callable to bind to. :type method: Callable :raises PageError: Raised if a function exists already with given "name". .. py:method:: set_credentials(credentials: dict[Literal['username', 'password'], str]) -> None :async: Set the credentials to use for HTTP authentication. Wrapper for `Page.network_manager.set_credentials`. :param credentials: A dictionary with credentials, keyed as "username" and "password". :type credentials: dict[str, str] .. py:method:: set_extra_http_headers(headers: dict[str, str]) -> None :async: Set extra headers to be sent with every request. Wrapper for `Page.network_manager.set_extra_http_headers`. :param extra_http_headers: A dictionary of headers. :type extra_http_headers: dict[str, str] :raises ValueError: Raised if any header value is not string. .. py:method:: set_user_agent(user_agent: str, user_agent_metadata: str | None = None) -> None :async: Update the user agent to be sent with every request. Wrapper for `Page.network_manager.set_user_agent`. :param user_agent: User agent string. :type user_agent: str :param user_agent_metadata: Experimental, used to specify user agent client hints to emulate. :type user_agent_metadata: str | None, optional .. py:method:: metrics() -> dict[str, Any] :async: Return dictionary with current values of runtime metrics. :returns: Runtime metrics as dictionary. :rtype: dict[str, Any] .. py:method:: content() -> str :async: Get encoded string representation of HTML in this `Page.main_frame`. Wrapper for `Page.main_frame.content`. :returns: HTML content. :rtype: str .. py:method:: set_content(html: str) -> None :async: Set the value of the HTML on this `Page.main_frame`. Wrapper for `Page.main_frame.set_content`. This does not change the value of the "document" request's response, it only changes what is shown in the window. Response values can be changed by intercepting requests or responses, see `Page.on` for more. :param html: HTML content to set to. :type html: str .. py:method:: goto(url: str, timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') -> mokr.network.Response | None :async: Navigate to the given `url`. :param url: URL to navigate to. Should be fully-qualified, starting with "https://" or "http://" (allowed if `ignore_https_errors`). :type url: str :param timeout: Time in milliseconds to wait for `wait_until` event. Defaults to None. :type timeout: int | None, optional :param wait_until: Event(s) to wait for, can be one or some combination of "load", "domcontentloaded", "networkidle", and "networkalmostidle". Defaults to "load". :type wait_until: list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional :raises PageError: Raised if error encountered during navigation. :raises MokrTimeoutError: Raised if timeout exceeded before all expected `wait_until` events are recieved. :returns: Last response recieved after all redirects, if any. :rtype: Response | None .. py:method:: go_back(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') -> mokr.network.Response | None :async: Navigate back in history. :param timeout: Time in milliseconds to wait for `wait_until` event. Defaults to None. :type timeout: int | None, optional :param wait_until: Event(s) to wait for, can be one or some combination of "load", "domcontentloaded", "networkidle", and "networkalmostidle". Defaults to "load". :type wait_until: list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional :returns: History `mokr.network.Response`, if any. :rtype: Response | None .. py:method:: go_forward(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') -> mokr.network.Response | None :async: Navigate next in history. :param timeout: Time in milliseconds to wait for `wait_until` event. Defaults to None. :type timeout: int | None, optional :param wait_until: Event(s) to wait for, can be one or some combination of "load", "domcontentloaded", "networkidle", and "networkalmostidle". Defaults to "load". :type wait_until: list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional :returns: History `mokr.network.Response`, if any. :rtype: Response | None .. py:method:: refresh(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') -> mokr.network.Response | None :async: Refresh (reload) the current page. :param timeout: Time in milliseconds to wait for `wait_until` event. Defaults to None. :type timeout: int | None, optional :param wait_until: Event(s) to wait for, can be one or some combination of "load", "domcontentloaded", "networkidle", and "networkalmostidle". Defaults to "load". :type wait_until: list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional :raises MokrTimeoutError: Raised if timeout exceeded before all expected `wait_until` events are recieved. :returns: Last response recieved after all redirects, if any. :rtype: Response | None .. py:method:: wait_for_navigation(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') -> mokr.network.Response | None :async: Wait for navigation to occur. Navigation is triggered by `Page.goto`, `Page.refresh`, redirects, and history (`Page.go_back` and `Page.go_forward`). Note that anchor navigation will not and history navigation may not yield any `mokr.network.Response` objects. :param timeout: Time in milliseconds to wait for `wait_until` event. Defaults to None. :type timeout: int | None, optional :param wait_until: Event(s) to wait for, can be one or some combination of "load", "domcontentloaded", "networkidle", and "networkalmostidle". Defaults to "load". :type wait_until: list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional :raises MokrTimeoutError: Raised if timeout exceeded before all expected `wait_until` events are recieved. :returns: Last response recieved after all redirects, if any. :rtype: Response | None .. py:method:: wait_for_request(url: str | None = None, method: Callable | None = None, timeout: int | None = 30000) -> mokr.network.Request :async: Wait for a `mokr.network.Request` whose `url` matches the `url` or that evaluates to True when passed to `method`. :param url: URL to wait. Defaults to None. :type url: str | None, optional :param method: Callable to pass `mokr.network.Request`s emitted by `Page.network_manager` to. Defaults to None. :type method: Callable | None, optional :param timeout: Time in milliseconds to wait. Defaults to 30000. :type timeout: int | None, optional :raises ValueError: Raised if neither `url` nor `method` given. :returns: First matching `mokr.network.Request`. :rtype: Request .. py:method:: wait_for_response(url: str | None = None, method: Callable | None = None, timeout: int | None = 30000) -> mokr.network.Response :async: Wait for a `mokr.network.Response` whose `url` matches the `url` or that evaluates to True when passed to `method`. :param url: URL to wait. Defaults to None. :type url: str | None, optional :param method: Callable to pass `mokr.network.Response`s emitted by `Page.network_manager` to. Defaults to None. :type method: Callable | None, optional :param timeout: Time in milliseconds to wait. Defaults to 30000. :type timeout: int | None, optional :raises ValueError: Raised if neither `url` nor `method` given. :returns: First matching `mokr.network.Response`. :rtype: Request .. py:method:: bring_to_front() -> None :async: Bring this `Page` to front (activate tab). .. py:method:: set_javascript_enabled(choice: bool) -> None :async: Enable or disable JavaScript on this `Page`. :param choice: True to enable, False to disable. :type choice: bool .. py:method:: set_bypass_csp(choice: bool) -> None :async: Enable or disable the target page's Content Security Policy. Note this should be called before navigation to the domain as this happens at CSP initialization. :param choice: True to enable, False to disable. :type choice: bool .. py:method:: emulate_media(media_type: Literal['screen', 'print'] | None = None) -> None :async: Emulate CSS media type on target page. :param media_type: Media type to emulate; one of "screen", "print", or None. Defaults to None. :type media_type: Literal["screen", "print"] | None, optional :raises ValueError: _description_ .. py:method:: set_viewport(viewport: dict) -> None :async: Run viewport adjustments based off given `viewport` parameters. Not all viewport options are considered, only: "isMobile", "width", "height", "deviceScaleFactor", "isLandscape", and "hasTouch". :param viewport: The parameters to adjust the viewport to. :type viewport: dict[str, bool | int] .. py:method:: evaluate(page_function: str, *args: Any, force_expr: bool = False) -> dict | None :async: Execute a JavaScript function with given arguments. Runs this `Page`'s default `mokr.frame.Frame.evaluate`. :param page_function: JavaScript function to run. :type page_function: str :param force_expr: If True, treat `page_function` as an expression. Otherwise, automatically determine if it is a function or an expression. Defaults to False. :type force_expr: bool :raises mokr.exceptions.NetworkError: :raises either evaluating the function or requesting the resulting object.: :returns: The decoded object (dict) via `mokr.execution.JavascriptHandle.json` or None if a known error occurs decoding it. :rtype: dict | None .. py:method:: evaluate_on_new_document(page_function: str, *args: str) -> None :async: Attach a function that will be evaluated on every new document. This occurs when a page or frame is navigated or attached. :param page_function: JavaScript function to attach. :type page_function: str .. py:method:: set_request_cache(choice: bool = True) -> None :async: Enable or disable request caching. Request caching caches requests in the browser, not `mokr.network.Request` objects. Does not check if request caching was enabled already by `Page.network_manager`. :param enabled: True to enable, False to disable. Defaults to True. :type enabled: bool, optional .. py:method:: screenshot(file_type: Literal['png', 'jpeg'] | None = None, file_path: str | None = None, jpeg_quality: int | None = None, full_page: bool = False, clip: dict[str, int] | None = None, omit_background: bool = False, encoding: Literal['binary', 'base64'] = 'binary', scale: int | float = 1) -> bytes :async: Take a screenshot of the page viewport. :param file_type: File type to save the image as. Defaults to "png" if None. :type file_type: Literal["png", "jpeg"] | None, optional :param file_path: Path to save image to. If given without `file_type`, the type will be inferred. Defaults to None. :type file_path: str | None, optional :param jpeg_quality: JPEG quality, 0-100 (only applicable if type is or is inferred to be JPEG. Defaults to 100 if None. :type jpeg_quality: int | None, optional :param full_page: Take a screenshot of the entire page if True, otherwise use the current viewport. Defaults to False. :type full_page: bool, optional :param clip: Applicable viewport settings to crop by. Defaults to None. :type clip: dict[str, int] | None, optional :param omit_background: Make the background transparent if True. Not supported on Firefox. Defaults to False. :type omit_background: bool, optional :param encoding: Encoding type to return the image data as. Defaults to "binary". :type encoding: Literal["binary", "base64"], optional :param scale: Image scale, 0-1. Defaults to 1. :type scale: int | float, optional :raises ValueError: Raised if `file_type` isn't given and can't be inferred as a supported type from `file_path`, if given. :returns: The image content as bytes or base64 encoded bytes. :rtype: bytes .. py:method:: pdf(file_path: str | None = None, scale: int | float = 1, display_header_footer: bool = False, header_template: str = None, footer_template: str = None, print_background: bool = False, landscape: bool = False, page_ranges: str = None, paper_format: str = 'letter', width: str = None, height: str = None, margin: dict = None, prefer_css_page_size: bool = False) -> bytes :async: Generate a PDF of the current page. `Page.pdf` generates a pdf of the page with "print" css media. To generate a pdf with screen media, first call `page.emulate_media("screen")`. The generated PDF will have modified colors for printing; this can be overriden by setting "-webkit-print-color-adjust" to "exact" in the page's stylesheet. :param file_path: File path to write output to, if any. Defaults to None. :type file_path: str | None, optional :param scale: Scale the PDF, 0-1. Defaults to 1. :type scale: int | float, optional :param display_header_footer: Display header and footer. Defaults to False. :type display_header_footer: bool, optional :param header_template: HTML template for the print header. Should be valid HTML markup with following HTML classes used to inject printing values into them: date: formatted print date title: document title url: document location pageNumber: current page number totalPages: total pages in the document For example, `` would generate span containing the title. Defaults to None. :type header_template: str, optional :param footer_template: Same as `header_template` but for the page footer. Defaults to None. :type footer_template: str, optional :param print_background: Print background graphics. Defaults to False. :type print_background: bool, optional :param landscape: Orient the PDF as landscape if True, otherwise as portrait. Defaults to False. :type landscape: bool, optional :param page_ranges: Page ranges to print, can be individual such as "7" or numerous such as "2-4,7,11-17". Defaults to all if None. :type page_ranges: str, optional :param paper_format: Paper format, overrides width/height. Formats are: "letter": 8.5in x 11in "legal": 8.5in x 14in "tabloid": 11in x 17in "ledger": 17in x 11in "a0": 33.1in x 46.8in "a1": 23.4in x 33.1in "a2": 16.5in x 23.4in "a3": 11.7in x 16.5in "a4": 8.27in x 11.7in "a5": 5.83in x 8.27in "a6": 4.13in x 5.83in Defaults to "letter". :type paper_format: str, optional :param width: Page width. Accepts units, defaults to pixels if not provided. Units: "px": pixel "in": inch "cm": centimeter "mm": millimeter Defaults to None. :type width: str, optional :param height: Page width. Accepts the same units as width. Defaults to None. :type height: str, optional :param margin: Margin values, can include any combination of "top", "bottom", "left", and "right". Accepts the same unit values as `width` and `height`. Defaults to None. :type margin: dict, optional :param prefer_css_page_size: Any CSS "@page" size. Overrides values from `paper_format`, `width`, and `height`. Defaults to False. :type prefer_css_page_size: bool, optional :raises ValueError: Raised if unknown paper format given. :returns: File content as bytes. :rtype: bytes .. py:method:: title() -> str :async: Get the title for this `Page.main_frame`. Wrapper for `Page.main_frame.title`. :returns: Page title. :rtype: str .. py:method:: close(run_before_unload: bool = False) -> None :async: Close the remote page. :param run_before_unload: Whether to run handlers registered to "Window.beforeunload". Defaults to False. :type run_before_unload: bool, optional :raises PageError: Raised if the remote connection has already been closed. .. py:method:: click(selector: str, button: Literal['left', 'right', 'middle'] = 'left', click_count: int = 1, delay: int | float | None = 1000) -> None :async: Click the first element that matches `selector`. Wrapper for `Page.main_frame.click`. This method is a shortcut for running `Page.query_selector` and then running `mokr.execution.ElementHandle.click` on the resultant ElementHandle. In either case, an element will be scrolled into view if needed, and the center of it clicked with the bound `Page.mouse`. :param selector: Selector to query element by. :type selector: str :param button: Mouse button to click with. Defaults to "left". :type button: Literal["left", "right", "middle"], optional :param click_count: Number of clicks to run. Defaults to 1. :type click_count: int, optional :param delay: Time in milliseconds to wait before each click. Defaults to 1000. :type delay: int | float | None, optional :raises PageError: Raised if no element is found with given `selector`. .. py:method:: hover(selector: str) -> None :async: Mouse hover over the first element that matches `selector`. Wrapper for `Page.main_frame.hover`. :raises PageError: Raised if no element is found with given `selector`. :param selector: Selector to query element by. :type selector: str .. py:method:: focus(selector: str) -> None :async: Focus on the first element that matches `selector`. Wrapper for `Page.main_frame.focus`. :raises PageError: Raised if no element is found with given `selector`. :param selector: Selector to query element by. :type selector: str .. py:method:: select(selector: str, values: list[str]) -> list[str] :async: Select options on a "select" element. Wrapper for `Page.main_frame.select`. :param selector: Selector to query element by. :type selector: str :param values: List of string options to select by. :type values: list[str] :returns: List of selected values. :rtype: list[str] .. py:method:: type_text(selector: str, text: str, delay: int | float = 0) -> None :async: Focus on the first element that matches `selector` and type characters into it. Wrapper for `Page.main_frame.type_text`. Note that modifier keys do not alter text case, meaning sending `mokr.input.Keyboard.press("shift")` and typing `Page.type_text("input", "mokr")` will not type "MOKR" into the it. :raises PageError: Raised if no element is found with given `selector`. :param selector: Selector to query element by. :type selector: str :param text: Text to type. :type text: str :param delay: Time in milliseconds to wait between each character typed. Defaults to 0. :type delay: int | float, optional .. py:method:: wait_for_timeout(timeout: int | float) -> Awaitable[None] Wait for the given amount of time. Same as `asyncio.sleep`. Wrapper for `Page.main_frame.wait_for_timeout`. :param timeout: Time in milliseconds to wait. :type timeout: int | float :returns: Task to be awaited. :rtype: Awaitable[None] .. py:method:: wait_for_selector(selector: str, visible: bool = False, hidden: bool = False, timeout: int = 30000) -> Awaitable[mokr.execution.ElementHandle] Wait for element that matches `selector` to appear in DOM. If element is in DOM already when called, return immediately. Wrapper for `Page.main_frame.wait_for_selector`. :param selector: Selector to query element by. :type selector: str :param visible: Element must also not be hidden. Defaults to False. :type visible: bool, optional :param hidden: Element must also be hidden. Defaults to False. :type hidden: bool, optional :param timeout: Time in milliseconds to wait. Defaults to 30000. :type timeout: int, optional :raises MokrTimeoutError: Raised if timeout exceeded before element found. :returns: Newly created `mokr.execution.ElementHandle` from found object. :rtype: Awaitable[ElementHandle] .. py:method:: wait_for_xpath(xpath: str, visible: bool = False, hidden: bool = False, timeout: int = 30000) -> Awaitable[mokr.execution.ElementHandle] Wait for element that matches `xpath` expression to appear in DOM. If element is in DOM already when called, return immediately. Wrapper for `Page.main_frame.wait_for_xpath`. :param xpath: Expression to query element by. :type xpath: str :param visible: Element must also not be hidden. Defaults to False. :type visible: bool, optional :param hidden: Element must also be hidden. Defaults to False. :type hidden: bool, optional :param timeout: Time in milliseconds to wait. Defaults to 30000. :type timeout: int, optional :raises MokrTimeoutError: Raised if timeout exceeded before element found. :returns: Newly created `mokr.execution.ElementHandle` from found object. :rtype: Awaitable[ElementHandle] .. py:method:: wait_for_function(page_function: str, polling: Literal['raf', 'mutation'] | int | float = 'raf', timeout: int = 30000) -> Awaitable[mokr.execution.JavascriptHandle] Wait until the given `page_function` returns a truthy value. Wrapper for `Page.main_frame.wait_for_function`. :param page_function: JavaScript function to run. :type page_function: str :param polling: Polling type; if set to "raf", executes continously in "requestAnimationFrame", else if set to "mutation" executes only on DOM mutations. Defaults to "raf". :type polling: Literal["raf", "mutation"] | int | float, optional :param timeout: Time in milliseconds to wait. Defaults to 30000. :type timeout: int, optional :returns: JavascriptHandle from JavaScript `page_function` successful result. :rtype: Awaitable[JavascriptHandle] .. py:method:: fetch(url: str | None = None, timeout: int = None, request: mokr.network.Request | None = None, body: str | None = None, browsing_topics: bool | None = None, cache: Literal['default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cache'] | None = None, credentials: Literal['omit', 'same-origin', 'include'] | None = None, headers: dict | None = None, method: str = 'GET', mode: Literal['cors', 'no-cors', 'same-origin'] = None, priority: Literal['high', 'low', 'auto'] | None = None, redirect: Literal['follow', 'error', 'manual'] | None = None, referrer: str | None = None, referrer_policy: Literal['no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url'] | None = None) -> mokr.network.Response :async: Send a fetch request. Wrapper for `Page.fetch_domain.fetch`. Note that fetch is sensitive to the current site's CORS settings. Additionally, trying to send a fetch request before the DOM loads can hang forever. :param url: The url to request. Ignored if `request` is given. Defaults to None. :type url: str | None, optional :param timeout: Time in milliseconds to wait. Defaults to None. :type timeout: int, optional :param request: A request object to pull `url`, `method`, and `headers` from. Defaults to None. :type request: Request | None, optional :param body: Body to add to the request. Defaults to None. :type body: str | None, optional :param browsing_topics: If True, selected topics will be sent in a Sec-Browsing-Topics header with the associated request. Defaults to None. :type browsing_topics: bool | None, optional :param cache: How the request should interact with the HTTP cache. One of: "default", "no-store", "reload", "no-cache", "force-cache", or "only-if-cache". Defaults to None. :type cache: Literal[str] :param credentials: How to handle credentials. One of "omit", "same-origin", or "include". Defaults to None. :type credentials: Literal[str] | None, optional :param headers: Headers to pass with the request. Defaults to None. :type headers: dict | None, optional :param method: HTTP method. Defaults to "GET". :type method: str, optional :param mode: CORS mode to use. Defaults to None. :type mode: Literal["cors", "no-cors", "same-origin"], optional :param priority: Priority of request relative to others. Defaults to None. :type priority: Literal["high", "low", "auto"] | None, optional :param redirect: How to handle redirects. Defaults to None ("follow"). :type redirect: Literal["follow", "error", "manual"] | None, optional :param referrer: Request referrer. Defaults to None. :type referrer: str | None, optional :param referrer_policy: The referrer policy to use. One of "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", or "unsafe-url". Defaults to None ("strict-origin-when-cross-origin"). :type referrer_policy: Literal[str] :raises ValueError: Raised if neither `url` nor `request` given. :raises NetworkError: Raised if no response found when request resolves. :returns: Last response recieved after all redirects, if any. :rtype: Response .. py:method:: send(url: str, method: mokr.constants.HTTP_METHODS = 'GET', params: dict | None = None, headers: dict | None = None, data: dict | None = None, json: dict | None = None, **httpx_request_kwargs) -> mokr.network.Response :async: Send an HTTP request. Wrapper for `Page.http_domain.send`. :param url: The url to request. :type url: str :param method: HTTP method. Defaults to "GET". :type method: Literal[str], optional :param params: Parameters to encode in the URL before sending. Defaults to None (omitted). :type params: dict | None, optional :param headers: Additional headers to send with this request beyond what was set when the client was created. Defaults to None (omitted). :type headers: dict | None, optional :param data: Data payload to deliver with request (form-encoded data). Only for "PUT", "POST", and "PATCH". Defaults to None (omitted). :type data: dict | None, optional :param json: Data payload to deliver with request (JSON-encoded data). Only for "PUT", "POST", and "PATCH". Defaults to None (omitted). :type json: dict | None, optional :raises ValueError: Raised if invalid HTTP method given or `data` or `json` arguments given with incompatible methods. :returns: A `mokr.network.Response` created from the `httpx.Response`. All redirects will also be created, and original requests and responses will be accessible from the `mokr.network` objects. :rtype: Response .. py:class:: Target(browser: mokr.browser.Browser, target_info: dict, browser_context: mokr.browser.context.BrowserContext, session_factory: Callable, ignore_https_errors: bool, default_viewport: dict | None, screenshot_task_queue: list, loop: asyncio.AbstractEventLoop, proxy_credentials: dict | None = None, user_agent_data: dict[str, str] | None = None) Representative of a remote target. Targets are a somewhat obscure concept, they can be a browser, frame, page, worker, or more. For the purposes of this package, only browser, pages, and workers are tracked explicitly. Full list of target types can be found at `devtools_agent_host_impl.cc` at https://source.chromium.org/chromium/chromium/src/. :param browser: Parent `mokr.browser.Browser`. :type browser: Browser :param target_info: The "targetInfo" in the event emitted that triggered this object's initialisation. :type target_info: dict :param browser_context: The `mokr.browser.BrowserContext` that this spawned from. :type browser_context: BrowserContext :param session_factory: Callable that creates a new `mokr.connection.DevtoolsConnection` for this target. :type session_factory: Callable :param ignore_https_errors: Whether network security errors should be ignored or not. Inherited from parent `mokr.browser.Browser`. :type ignore_https_errors: bool :param default_viewport: Default viewport configuration. Inherited from parent `mokr.browser.Browser`. :type default_viewport: dict | None :param screenshot_task_queue: The screenshot task queue, empty by default. Inherited from parent `mokr.browser.Browser`. :type screenshot_task_queue: list :param loop: The `asyncio` loop that is tracked under the `mokr.browser.Browser`'s `mokr.connection.Connection`. :type loop: asyncio.AbstractEventLoop :param proxy_credentials: (dict | None, optional): Dictionary with proxy credentials keyed as "username" and "password". Credentials should be for the proxy the browser process is bound to. Inherited from parent `mokr.browser.Browser`. :param user_agent_data: A dictionary containing the user agent and an indicator to whether it was the original or an override. :type user_agent_data: dict[str, str] | None, optional .. py:property:: url :type: str Get url of this target. .. py:property:: kind :type: KINDS Get type of this target. Type may be on of "page", "background_page", "service_worker", "browser", or "other". .. py:property:: browser :type: mokr.browser.Browser The `mokr.browser.Browser` that owns the `mokr.browser.BrowserContext` that this target was initialised from. .. py:property:: browser_context :type: mokr.browser.context.BrowserContext `mokr.browser.BrowserContext` this target was initialised from. .. py:property:: opener :type: Target | None The parent `Target` that spawned this, if any. .. py:method:: create_devtools_connection() -> mokr.connection.DevtoolsConnection :async: Initialise the `mokr.connection.DevtoolsConnection` that will be bound to this `Target`. :returns: The new `mokr.connection.DevtoolsConnection`. :rtype: DevtoolsConnection .. py:method:: page() -> mokr.browser.page.Page | None :async: Get the `mokr.browser.Page` object attached to this `Target`. Only applicable if `Target.kind` is "page" or "background_page". :returns: Associated `mokr.browser.Page`, if any. :rtype: Page | None .. py:class:: ViewportManager(client: mokr.connection.connection.DevtoolsConnection) Handler for adjusting the browser viewport. Can adjust size and enable functionality such as touchmode. :param client: `mokr.network.DevtoolsConnection` object, shared from the parent `mokr.browser.Page`. :type client: DevtoolsConnection .. py:method:: emulate_viewport(viewport: dict[str, bool | int]) -> bool :async: Run viewport adjustments based off given `viewport` parameters. Not all viewport options are considered, only: "isMobile", "width", "height", "deviceScaleFactor", "isLandscape", and "hasTouch". :param viewport: The parameters to adjust the viewport to. :type viewport: dict[str, bool | int] :raises TypeError: Raised if "width" or "height" in `viewport` are not positive integers. :returns: True to indicate if a reload of the page is needed to affect the changes sent. False if not. :rtype: bool .. py:class:: WebWorker(client: mokr.connection.DevtoolsConnection, url: str, console_api_callback: Callable, exception_thrown: Callable) Bases: :py:obj:`pyee.EventEmitter` Represents a web worker on the page. This object is created and destroyed by it's parent `mokr.browser.Page`. :param client: A `mokr.connection.DevtoolsConnection` spawned by the parent `mokr.browser.Page`. :type client: DevtoolsConnection :param url: The "url" present in the triggering event's "targetInfo". :type url: str :param console_api_callback: Callback to run when the console is called, if no listener's are present for this on the `mokr.browser.Page`, will delete the handle due to given default callback from parent `Page`. :type console_api_callback: Callable :param exception_thrown: Callback to run if exception occurs. :type exception_thrown: Callable .. py:attribute:: console_api_callback .. py:property:: url :type: str URL associated with the event that triggered this worker. .. py:method:: execution_context() -> mokr.execution.context.ExecutionContext :async: Return the newly created `mokr.execution.ExecutionContext`. :returns: `mokr.execution.ExecutionContext`. :rtype: ExecutionContext .. py:method:: evaluate(page_function: str, *args: Any) -> dict | None :async: Execute a JavaScript function with given arguments. Run this `WebWorker`'s `mokr.execution.ExecutionContext.evaluate`. :param page_function: JavaScript function to run. :type page_function: str :raises mokr.exceptions.NetworkError: :raises either evaluating the function or requesting the resulting object.: :returns: The decoded object (dict) via `mokr.execution.JavascriptHandle.json` or None if a known error occurs decoding it. :rtype: dict | None .. py:method:: evaluate_handle(page_function: str, *args: Any) -> mokr.execution.context.JavascriptHandle :async: Execute a JavaScript function with given arguments. Run this `WebWorker`'s `mokr.execution.ExecutionContext.evaluate_handle`. :param page_function: JavaScript function to run. :type page_function: str :returns: `mokr.execution.JavascriptHandle`. :rtype: JavascriptHandle