mokr.browser

Submodules

Package Contents

Classes

Browser

This class is created upon connect to a browser. It is essentially a

ConsoleMessage

Representation of console messages, dispatched on console event in

BrowserContext

Browser context within the browser process. Contexts are independent

Page

Representative of a single tab within the browser (more specifically,

Target

Representative of a remote target.

ViewportManager

Handler for adjusting the browser viewport. Can adjust size and

WebWorker

Represents a web worker on the page. This object is created and

class mokr.browser.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: pyee.EventEmitter

This class is created upon connect to a browser. It is essentially a container for the individual pages and browser contexts.

Parameters:
  • browser_type (Literal["chrome", "firefox"]) – The type of browser.

  • connection (mokr.network.Connection) – Websocket connection.

  • context_ids (list[str]) – Browser context identifiers.

  • ignore_https_errors (bool) – Ignore site security errors.

  • default_viewport (dict | None) – Default viewport configuration.

  • process (Popen | None, optional) – Local browser process, if any. Defaults to None.

  • close_callback (Callable | None, optional) – Callback to run on close. Defaults to None.

  • 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.

  • default_user_agent (str, optional) – Default user agent to use on all new pages.

property kind: str

One of “chrome” or “firefox”.

property process: subprocess.Popen | None

The local browser process. If created via mokr.connect, will return None.

property version: str

Get browser version (product from browser full version info.)

property user_agent: 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.

property browser_contexts: 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.

property ws_endpoint: str

The websocket URL that this Browser’s mokr.connection.Connection object is using.

async first_page() mokr.browser.page.Page | None

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.

Return type:

Page | None

async ready() Browser

Enable target discovery in the remote connection.

Returns:

This Browser class.

Return type:

Browser

async create_incognito_browser_context() mokr.browser.context.BrowserContext

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.

Return type:

BrowserContext

async new_page() mokr.browser.page.Page

Spawn a new page within the default context.

Returns:

A new mokr.browser.Page at “about:blank”.

Return type:

Page

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.

Return type:

list[Target]

async pages() list[mokr.browser.page.Page]

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.

Return type:

list[Page]

async close() None

Run the close_callback given during initialisation.

async disconnect() None

Disconnect the Browser’s Connection object’s websocket connection and fail any Browser.targets that haven’t finished initialising.

class mokr.browser.ConsoleMessage(kind: str, text: str, args: list[mokr.execution.JavascriptHandle] = None)

Representation of console messages, dispatched on console event in mokr.browser.Page.

Parameters:
  • kind (str) – The type of message.

  • text (str) – The message body.

  • args (list[JavascriptHandle], optional) – Arguments attached to this message. Defaults to None.

property kind: str

Return type of this message.

property text: str

Return text representation of the message body.

property args: list[mokr.execution.JavascriptHandle]

Return list of argumentss (JavascriptHandle) of this message.

class mokr.browser.BrowserContext(browser: mokr.browser.Browser, context_id: str | None)

Bases: 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.

Parameters:
  • browser (Browser) – Parent mokr.browser.Browser object from which the context was spawned.

  • context_id (str | None) – The context identifier (may be None).

property incognito: 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.

property browser: mokr.browser.Browser

The mokr.browser.Browser object this context is attached to.

targets() list[mokr.browser.target.Target]

A list of all `mokr.browser.Target`s in this context.

Returns:

All initialised targets within this context.

Return type:

list[Target]

async pages() list[mokr.browser.page.Page]

A list of all `mokr.browser.Page`s in this context.

Returns:

All pages within this context.

Return type:

list[Page]

async first_page() mokr.browser.page.Page

Return the first page in BrowserContext.pages. If no pages active, returns None.

Returns:

First active page in this context, if any.

Return type:

Page | None

async new_page() mokr.browser.page.Page

Spawn a new page.

Returns:

A new mokr.browser.Page at “about:blank”.

Return type:

Page

async close() None

Close the context. Can only be done on incognito contexts.

Raises:

BrowserError – Raised if called from the default context.

class mokr.browser.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: 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.

Parameters:
  • browser (Browser) – Parent mokr.browser.Browser.

  • client (DevtoolsConnection) – From parent mokr.browser.Target.

  • target (Target) – Spawning mokr.browser.Target.

  • frame_tree (dict) – Frame tree structure from remote connection.

  • ignore_https_errors (bool) – Ignore site security errors. Inherited from parent mokr.browser.Browser.

  • user_agent (str) – User agent for this page. Inherited from parent mokr.browser.Browser.

  • screenshot_task_queue (list, optional) – The screenshot task queue, empty by default. Inherited from parent mokr.browser.Browser.

  • 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.

property target: mokr.browser.target.Target

Parent mokr.browser.Target this Page was spawned from.

property browser: mokr.browser.Browser

Parent mokr.browser.Browser this Page belongs to.

property main_frame: mokr.frame.Frame | None

This Page’s mokr.frame.FrameManager’s main mokr.frame.Frame.

property network_manager: mokr.network.NetworkManager | None

This Page’s mokr.network.NetworkManager.

property fetch_domain: mokr.network.FetchDomain

This Page’s mokr.fetch.FetchDomain.

property http_domain: mokr.network.HttpDomain

This Page’s mokr.network.HttpDomain.

property keyboard: mokr.input.Keyboard

This Page’s mokr.input.Keyboard.

property mouse: mokr.input.Mouse

This Page’s mokr.input.Mouse.

property touchscreen: mokr.input.Touchscreen

This Page’s mokr.input.Touchscreen.

property frames: list[mokr.frame.Frame]

List of all mokr.frame.Frames within this Page.

property workers: list[mokr.browser.worker.WebWorker]

List of all mokr.browser.WebWorker`s within this `Page.

property url: str

The URL the Page is currently at.

property viewport: dict | None

Current viewport configuration, if any.

property user_agent: str | None

The user agent given to override on all requests, if any.

property is_closed: 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.

property browser_type: str

One of “chrome” or “firefox”.

async static 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

Async constructor for this class. Necessary to run some asyncronous post-initialisation tasks.

Parameters:
  • browser (Browser) – Parent mokr.browser.Browser.

  • client (DevtoolsConnection) – From parent mokr.browser.Target.

  • target (Target) – Spawning mokr.browser.Target.

  • ignore_https_errors (bool) – Ignore site security errors. Inherited from parent mokr.browser.Browser.

  • default_viewport (dict | None) – Default viewport configuration.

  • screenshot_task_queue (list, optional) – The screenshot task queue, empty by default. Inherited from parent mokr.browser.Browser.

  • 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.

  • user_agent_data (dict[str, str] | None, optional) – A dictionary containing the user agent and an indicator to whether it was the original or an override.

Returns:

New Page with necessary remote configuration enabled.

Return type:

Page

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.

Parameters:
  • event (str) – Event name to listen for.

  • method (Callable | None) – Method to call when event is emitted.

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)
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.

Parameters:

sync_cookies (Literal["both", "http", "page", "none"], optional) – Whether to sync cookies between the HttpDomain and the parent Page before/after each request and response. Defaults to “both”.

async set_request_interception_enabled(choice: bool) None

Disable or enabled request interception (enabled by default). See Page.on for details on using the request interception callback chain.

Parameters:

choice (bool) – False to disable, True to enable.

async tap(selector: str) None

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.

Parameters:

selector (str) – Selector to query element by.

Raises:

PageError – Raised if no element is found with given selector.

async set_offline_mode(choice: bool) None

Enable or diable offline mode. Disabled by default. Wrapper for Page.network_manager.set_offline_mode.

Parameters:

enabled (bool) – False to disable, True to enable.

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.

Parameters:

timeout (int) – Milliseconds to wait. Use 0 for infinite.

async evaluate_handle(page_function: str, *args: Any) mokr.execution.JavascriptHandle

Execute a JavaScript function with given arguments. Runs this Page’s default mokr.frame.Frame.evaluate_handle.

Parameters:

page_function (str) – JavaScript function to run.

Raises:

PageError – Raised if the Page’s main mokr.frame.Frame fails to find its mokr.browser.ExecutionContext.

Returns:

mokr.execution.JavascriptHandle.

Return type:

JavascriptHandle

async query_objects(javascript_handle: mokr.execution.JavascriptHandle) mokr.execution.JavascriptHandle

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.

Parameters:

javascript_handle (JavascriptHandle) – A valid (not disposed) mokr.execution.JavascriptHandle object.

Raises:
  • PageError – Raised if the Page’s main mokr.frame.Frame fails to find its mokr.browser.ExecutionContext.

  • 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.

Return type:

JavascriptHandle

async query_selector(selector: str) mokr.execution.ElementHandle | None

Return the first element in the DOM that matches the selector, if any. Wrapper for Page.main_frame.query_selector.

Parameters:

selector (str) – Element selector to locate.

Returns:

ElementHandle if found or None.

Return type:

ElementHandle | None

async query_selector_all(selector: str) list[mokr.execution.ElementHandle]

Return all elements in the DOM that match the selector, if any. Wrapper for Page.main_frame.query_selector_all.

Parameters:

selector (str) – Element selector to locate.

Returns:

List of ElementHandle if any or empty list.

Return type:

list[ElementHandle]

async xpath(expression: str) list[mokr.execution.ElementHandle]

Return all elements in the DOM that match the expression, if any. Wrapper for Page.main_frame.xpath.

Parameters:

expression (str) – XPath expression to evaluate.

Returns:

List of ElementHandle if any or empty list.

Return type:

list[ElementHandle]

async cookies() list[dict[str, str | int | bool]]

Get all cookies accessible to the browser.

Returns:

List of dictionaries representing

each cookie.

Return type:

list[dict[str, str | int | bool]]

async get_cookies_by_urls(urls: list[str] | None = None) list[dict[str, str | int | bool]]

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.

Parameters:

urls (list[str] | None) – List of URLs to get cookies for. Defaults to None.

Returns:

List of dictionaries representing

each cookie.

Return type:

list[dict[str, str | int | bool]]

async delete_cookies(cookies: list[dict]) None

Delete a cookie from this Page.

Parameters:

cookies (list[dict]) – A list of dictionaries representing a cookie entry. Each dictionary must at minimum contain a “name”.

async set_cookies(cookies: list[dict]) None

Set a cookie on this Page.

Parameters:

cookies (list[dict]) – A list of dictionaries representing a cookie entry. Each dictionary must at minimum contain a “name” and a “value”.

Raises:

PageError – Raised if the current page is blank (”about:blank”) or is a data URL (starts with “data:”).

async embed_javascript(file_content: str = None, file_path: str = None, url: str = None, script_type: str = None) mokr.execution.ElementHandle

Add script tag to this Page.main_frame. Wrapper for Page.main_frame.embed_javascript.

Parameters:
  • file_content (str, optional) – Encoded file content for script to embed. If not given, must give file_path or url. Defaults to None.

  • file_path (str, optional) – File path for script to embed. If not given, must give file_content or url. Defaults to None.

  • url (str, optional) – URL for script to embed. If not given, must give file_content or file_path. Defaults to None.

  • script_type (str, optional) – Use “module” to load as JavaScript ES6 module, if not given, defaults to “text/javascript”. Defaults to None.

Raises:
  • ValueError – Raised if none of file_content, file_path, or url are given.

  • PageError – Raised if error occurs sending embed request to remote connection (from ElementHandleError).

Returns:

Newly embedded element.

Return type:

ElementHandle

async embed_style(file_content: str = None, file_path: str = None, url: str = None) mokr.execution.ElementHandle

Add style tag to this Page.main_frame. Wrapper for Page.main_frame.embed_style.

Parameters:
  • file_content (str, optional) – Encoded file content for style to embed. If not given, must give file_path or url. Defaults to None.

  • file_path (str, optional) – File path for style to embed. If not given, must give file_content or url. Defaults to None.

  • url (str, optional) – URL for style to embed. If not given, must give file_content or file_path. Defaults to None.

Raises:
  • ValueError – Raised if none of file_content, file_path, or url are given.

  • PageError – Raised if error occurs sending embed request to remote connection (from ElementHandleError).

Returns:

Newly embedded element.

Return type:

ElementHandle

async expose_function(name: str, method: Callable) None

Bind a remote JavaScript function “name” to local method. This will allow triggering local method by calling window["name"]() in the browser.

Parameters:
  • name (str) – Remote JavaScript function name.

  • method (Callable) – Local callable to bind to.

Raises:

PageError – Raised if a function exists already with given “name”.

async set_credentials(credentials: dict[Literal[username, password], str]) None

Set the credentials to use for HTTP authentication. Wrapper for Page.network_manager.set_credentials.

Parameters:

credentials (dict[str, str]) – A dictionary with credentials, keyed as “username” and “password”.

async set_extra_http_headers(headers: dict[str, str]) None

Set extra headers to be sent with every request. Wrapper for Page.network_manager.set_extra_http_headers.

Parameters:

extra_http_headers (dict[str, str]) – A dictionary of headers.

Raises:

ValueError – Raised if any header value is not string.

async set_user_agent(user_agent: str, user_agent_metadata: str | None = None) None

Update the user agent to be sent with every request. Wrapper for Page.network_manager.set_user_agent.

Parameters:
  • user_agent (str) – User agent string.

  • user_agent_metadata (str | None, optional) – Experimental, used to specify user agent client hints to emulate.

async metrics() dict[str, Any]

Return dictionary with current values of runtime metrics.

Returns:

Runtime metrics as dictionary.

Return type:

dict[str, Any]

async content() str

Get encoded string representation of HTML in this Page.main_frame. Wrapper for Page.main_frame.content.

Returns:

HTML content.

Return type:

str

async set_content(html: str) None

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.

Parameters:

html (str) – HTML content to set to.

async goto(url: str, timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') mokr.network.Response | None

Navigate to the given url.

Parameters:
  • url (str) – URL to navigate to. Should be fully-qualified, starting with “https://” or “http://” (allowed if ignore_https_errors).

  • timeout (int | None, optional) – Time in milliseconds to wait for wait_until event. Defaults to None.

  • wait_until (list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional) – Event(s) to wait for, can be one or some combination of “load”, “domcontentloaded”, “networkidle”, and “networkalmostidle”. Defaults to “load”.

Raises:
  • PageError – Raised if error encountered during navigation.

  • MokrTimeoutError – Raised if timeout exceeded before all expected wait_until events are recieved.

Returns:

Last response recieved after all redirects, if any.

Return type:

Response | None

async go_back(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') mokr.network.Response | None

Navigate back in history.

Parameters:
  • timeout (int | None, optional) – Time in milliseconds to wait for wait_until event. Defaults to None.

  • wait_until (list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional) – Event(s) to wait for, can be one or some combination of “load”, “domcontentloaded”, “networkidle”, and “networkalmostidle”. Defaults to “load”.

Returns:

History mokr.network.Response, if any.

Return type:

Response | None

async go_forward(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') mokr.network.Response | None

Navigate next in history.

Parameters:
  • timeout (int | None, optional) – Time in milliseconds to wait for wait_until event. Defaults to None.

  • wait_until (list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional) – Event(s) to wait for, can be one or some combination of “load”, “domcontentloaded”, “networkidle”, and “networkalmostidle”. Defaults to “load”.

Returns:

History mokr.network.Response, if any.

Return type:

Response | None

async refresh(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') mokr.network.Response | None

Refresh (reload) the current page.

Parameters:
  • timeout (int | None, optional) – Time in milliseconds to wait for wait_until event. Defaults to None.

  • wait_until (list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional) – Event(s) to wait for, can be one or some combination of “load”, “domcontentloaded”, “networkidle”, and “networkalmostidle”. Defaults to “load”.

Raises:

MokrTimeoutError – Raised if timeout exceeded before all expected wait_until events are recieved.

Returns:

Last response recieved after all redirects, if any.

Return type:

Response | None

async wait_for_navigation(timeout: int | None = None, wait_until: list[mokr.constants.LIFECYCLE_EVENTS] | mokr.constants.LIFECYCLE_EVENTS = 'load') mokr.network.Response | None

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.

Parameters:
  • timeout (int | None, optional) – Time in milliseconds to wait for wait_until event. Defaults to None.

  • wait_until (list[LIFECYCLE_EVENTS] | LIFECYCLE_EVENTS, optional) – Event(s) to wait for, can be one or some combination of “load”, “domcontentloaded”, “networkidle”, and “networkalmostidle”. Defaults to “load”.

Raises:

MokrTimeoutError – Raised if timeout exceeded before all expected wait_until events are recieved.

Returns:

Last response recieved after all redirects, if any.

Return type:

Response | None

async wait_for_request(url: str | None = None, method: Callable | None = None, timeout: int | None = 30000) mokr.network.Request

Wait for a mokr.network.Request whose url matches the url or that evaluates to True when passed to method.

Parameters:
  • url (str | None, optional) – URL to wait. Defaults to None.

  • method (Callable | None, optional) – Callable to pass mokr.network.Request`s emitted by `Page.network_manager to. Defaults to None.

  • timeout (int | None, optional) – Time in milliseconds to wait. Defaults to 30000.

Raises:

ValueError – Raised if neither url nor method given.

Returns:

First matching mokr.network.Request.

Return type:

Request

async wait_for_response(url: str | None = None, method: Callable | None = None, timeout: int | None = 30000) mokr.network.Response

Wait for a mokr.network.Response whose url matches the url or that evaluates to True when passed to method.

Parameters:
  • url (str | None, optional) – URL to wait. Defaults to None.

  • method (Callable | None, optional) – Callable to pass mokr.network.Response`s emitted by `Page.network_manager to. Defaults to None.

  • timeout (int | None, optional) – Time in milliseconds to wait. Defaults to 30000.

Raises:

ValueError – Raised if neither url nor method given.

Returns:

First matching mokr.network.Response.

Return type:

Request

async bring_to_front() None

Bring this Page to front (activate tab).

async set_javascript_enabled(choice: bool) None

Enable or disable JavaScript on this Page.

Parameters:

choice (bool) – True to enable, False to disable.

async set_bypass_csp(choice: bool) None

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.

Parameters:

choice (bool) – True to enable, False to disable.

async emulate_media(media_type: Literal[screen, print] | None = None) None

Emulate CSS media type on target page.

Parameters:

media_type (Literal["screen", "print"] | None, optional) – Media type to emulate; one of “screen”, “print”, or None. Defaults to None.

Raises:

ValueError – _description_

async set_viewport(viewport: dict) None

Run viewport adjustments based off given viewport parameters. Not all viewport options are considered, only: “isMobile”, “width”, “height”, “deviceScaleFactor”, “isLandscape”, and “hasTouch”.

Parameters:

viewport (dict[str, bool | int]) – The parameters to adjust the viewport to.

async evaluate(page_function: str, *args: Any, force_expr: bool = False) dict | None

Execute a JavaScript function with given arguments. Runs this Page’s default mokr.frame.Frame.evaluate.

Parameters:
  • page_function (str) – JavaScript function to run.

  • force_expr (bool) – If True, treat page_function as an expression. Otherwise, automatically determine if it is a function or an expression. Defaults to False.

Raises:
Returns:

The decoded object (dict) via

mokr.execution.JavascriptHandle.json or None if a known error occurs decoding it.

Return type:

dict | None

async evaluate_on_new_document(page_function: str, *args: str) None

Attach a function that will be evaluated on every new document. This occurs when a page or frame is navigated or attached.

Parameters:

page_function (str) – JavaScript function to attach.

async set_request_cache(choice: bool = True) None

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.

Parameters:

enabled (bool, optional) – True to enable, False to disable. Defaults to True.

async 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

Take a screenshot of the page viewport.

Parameters:
  • file_type (Literal["png", "jpeg"] | None, optional) – File type to save the image as. Defaults to “png” if None.

  • file_path (str | None, optional) – Path to save image to. If given without file_type, the type will be inferred. Defaults to None.

  • jpeg_quality (int | None, optional) – JPEG quality, 0-100 (only applicable if type is or is inferred to be JPEG. Defaults to 100 if None.

  • full_page (bool, optional) – Take a screenshot of the entire page if True, otherwise use the current viewport. Defaults to False.

  • clip (dict[str, int] | None, optional) – Applicable viewport settings to crop by. Defaults to None.

  • omit_background (bool, optional) – Make the background transparent if True. Not supported on Firefox. Defaults to False.

  • encoding (Literal["binary", "base64"], optional) – Encoding type to return the image data as. Defaults to “binary”.

  • scale (int | float, optional) – Image scale, 0-1. Defaults to 1.

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.

Return type:

bytes

async 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

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.

Parameters:
  • file_path (str | None, optional) – File path to write output to, if any. Defaults to None.

  • scale (int | float, optional) – Scale the PDF, 0-1. Defaults to 1.

  • display_header_footer (bool, optional) – Display header and footer. Defaults to False.

  • header_template (str, optional) –

    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, <span class=title></span> would generate span containing the title. Defaults to None.

  • footer_template (str, optional) – Same as header_template but for the page footer. Defaults to None.

  • print_background (bool, optional) – Print background graphics. Defaults to False.

  • landscape (bool, optional) – Orient the PDF as landscape if True, otherwise as portrait. Defaults to False.

  • page_ranges (str, optional) – Page ranges to print, can be individual such as “7” or numerous such as “2-4,7,11-17”. Defaults to all if None.

  • paper_format (str, optional) –

    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”.

  • width (str, optional) –

    Page width. Accepts units, defaults to pixels if not provided. Units:

    ”px”: pixel “in”: inch “cm”: centimeter “mm”: millimeter

    Defaults to None.

  • height (str, optional) – Page width. Accepts the same units as width. Defaults to None.

  • margin (dict, optional) – Margin values, can include any combination of “top”, “bottom”, “left”, and “right”. Accepts the same unit values as width and height. Defaults to None.

  • prefer_css_page_size (bool, optional) – Any CSS “@page” size. Overrides values from paper_format, width, and height. Defaults to False.

Raises:

ValueError – Raised if unknown paper format given.

Returns:

File content as bytes.

Return type:

bytes

async title() str

Get the title for this Page.main_frame. Wrapper for Page.main_frame.title.

Returns:

Page title.

Return type:

str

async close(run_before_unload: bool = False) None

Close the remote page.

Parameters:

run_before_unload (bool, optional) – Whether to run handlers registered to “Window.beforeunload”. Defaults to False.

Raises:

PageError – Raised if the remote connection has already been closed.

async click(selector: str, button: Literal[left, right, middle] = 'left', click_count: int = 1, delay: int | float | None = 1000) None

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.

Parameters:
  • selector (str) – Selector to query element by.

  • button (Literal["left", "right", "middle"], optional) – Mouse button to click with. Defaults to “left”.

  • click_count (int, optional) – Number of clicks to run. Defaults to 1.

  • delay (int | float | None, optional) – Time in milliseconds to wait before each click. Defaults to 1000.

Raises:

PageError – Raised if no element is found with given selector.

async hover(selector: str) None

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.

Parameters:

selector (str) – Selector to query element by.

async focus(selector: str) None

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.

Parameters:

selector (str) – Selector to query element by.

async select(selector: str, values: list[str]) list[str]

Select options on a “select” element. Wrapper for Page.main_frame.select.

Parameters:
  • selector (str) – Selector to query element by.

  • values (list[str]) – List of string options to select by.

Returns:

List of selected values.

Return type:

list[str]

async type_text(selector: str, text: str, delay: int | float = 0) None

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.

Parameters:
  • selector (str) – Selector to query element by.

  • text (str) – Text to type.

  • delay (int | float, optional) – Time in milliseconds to wait between each character typed. Defaults to 0.

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.

Parameters:

timeout (int | float) – Time in milliseconds to wait.

Returns:

Task to be awaited.

Return type:

Awaitable[None]

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.

Parameters:
  • selector (str) – Selector to query element by.

  • visible (bool, optional) – Element must also not be hidden. Defaults to False.

  • hidden (bool, optional) – Element must also be hidden. Defaults to False.

  • timeout (int, optional) – Time in milliseconds to wait. Defaults to 30000.

Raises:

MokrTimeoutError – Raised if timeout exceeded before element found.

Returns:

Newly created

mokr.execution.ElementHandle from found object.

Return type:

Awaitable[ElementHandle]

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.

Parameters:
  • xpath (str) – Expression to query element by.

  • visible (bool, optional) – Element must also not be hidden. Defaults to False.

  • hidden (bool, optional) – Element must also be hidden. Defaults to False.

  • timeout (int, optional) – Time in milliseconds to wait. Defaults to 30000.

Raises:

MokrTimeoutError – Raised if timeout exceeded before element found.

Returns:

Newly created

mokr.execution.ElementHandle from found object.

Return type:

Awaitable[ElementHandle]

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.

Parameters:
  • page_function (str) – JavaScript function to run.

  • polling (Literal["raf", "mutation"] | int | float, optional) – Polling type; if set to “raf”, executes continously in “requestAnimationFrame”, else if set to “mutation” executes only on DOM mutations. Defaults to “raf”.

  • timeout (int, optional) – Time in milliseconds to wait. Defaults to 30000.

Returns:

JavascriptHandle from JavaScript

page_function successful result.

Return type:

Awaitable[JavascriptHandle]

async 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

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.

Parameters:
  • url (str | None, optional) – The url to request. Ignored if request is given. Defaults to None.

  • timeout (int, optional) – Time in milliseconds to wait. Defaults to None.

  • request (Request | None, optional) – A request object to pull url, method, and headers from. Defaults to None.

  • body (str | None, optional) – Body to add to the request. Defaults to None.

  • browsing_topics (bool | None, optional) – If True, selected topics will be sent in a Sec-Browsing-Topics header with the associated request. Defaults to None.

  • cache (Literal[str]) – 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.

  • credentials (Literal[str] | None, optional) – How to handle credentials. One of “omit”, “same-origin”, or “include”. Defaults to None.

  • headers (dict | None, optional) – Headers to pass with the request. Defaults to None.

  • method (str, optional) – HTTP method. Defaults to “GET”.

  • mode (Literal["cors", "no-cors", "same-origin"], optional) – CORS mode to use. Defaults to None.

  • priority (Literal["high", "low", "auto"] | None, optional) – Priority of request relative to others. Defaults to None.

  • redirect (Literal["follow", "error", "manual"] | None, optional) – How to handle redirects. Defaults to None (“follow”).

  • referrer (str | None, optional) – Request referrer. Defaults to None.

  • referrer_policy (Literal[str]) – 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”).

Raises:
  • ValueError – Raised if neither url nor request given.

  • NetworkError – Raised if no response found when request resolves.

Returns:

Last response recieved after all redirects, if any.

Return type:

Response

async 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

Send an HTTP request. Wrapper for Page.http_domain.send.

Parameters:
  • url (str) – The url to request.

  • method (Literal[str], optional) – HTTP method. Defaults to “GET”.

  • params (dict | None, optional) – Parameters to encode in the URL before sending. Defaults to None (omitted).

  • headers (dict | None, optional) – Additional headers to send with this request beyond what was set when the client was created. Defaults to None (omitted).

  • data (dict | None, optional) – Data payload to deliver with request (form-encoded data). Only for “PUT”, “POST”, and “PATCH”. Defaults to None (omitted).

  • json (dict | None, optional) – Data payload to deliver with request (JSON-encoded data). Only for “PUT”, “POST”, and “PATCH”. Defaults to None (omitted).

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.

Return type:

Response

class mokr.browser.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/.

Parameters:
  • browser (Browser) – Parent mokr.browser.Browser.

  • target_info (dict) – The “targetInfo” in the event emitted that triggered this object’s initialisation.

  • browser_context (BrowserContext) – The mokr.browser.BrowserContext that this spawned from.

  • session_factory (Callable) – Callable that creates a new mokr.connection.DevtoolsConnection for this target.

  • ignore_https_errors (bool) – Whether network security errors should be ignored or not. Inherited from parent mokr.browser.Browser.

  • default_viewport (dict | None) – Default viewport configuration. Inherited from parent mokr.browser.Browser.

  • screenshot_task_queue (list) – The screenshot task queue, empty by default. Inherited from parent mokr.browser.Browser.

  • loop (asyncio.AbstractEventLoop) – The asyncio loop that is tracked under the mokr.browser.Browser’s mokr.connection.Connection.

  • 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.

  • user_agent_data (dict[str, str] | None, optional) – A dictionary containing the user agent and an indicator to whether it was the original or an override.

property url: str

Get url of this target.

property kind: KINDS

Get type of this target. Type may be on of “page”, “background_page”, “service_worker”, “browser”, or “other”.

property browser: mokr.browser.Browser

The mokr.browser.Browser that owns the mokr.browser.BrowserContext that this target was initialised from.

property browser_context: mokr.browser.context.BrowserContext

mokr.browser.BrowserContext this target was initialised from.

property opener: Target | None

The parent Target that spawned this, if any.

async create_devtools_connection() mokr.connection.DevtoolsConnection

Initialise the mokr.connection.DevtoolsConnection that will be bound to this Target.

Returns:

The new mokr.connection.DevtoolsConnection.

Return type:

DevtoolsConnection

async page() mokr.browser.page.Page | None

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.

Return type:

Page | None

class mokr.browser.ViewportManager(client: mokr.connection.connection.DevtoolsConnection)

Handler for adjusting the browser viewport. Can adjust size and enable functionality such as touchmode.

Parameters:

client (DevtoolsConnection) – mokr.network.DevtoolsConnection object, shared from the parent mokr.browser.Page.

async emulate_viewport(viewport: dict[str, bool | int]) bool

Run viewport adjustments based off given viewport parameters. Not all viewport options are considered, only: “isMobile”, “width”, “height”, “deviceScaleFactor”, “isLandscape”, and “hasTouch”.

Parameters:

viewport (dict[str, bool | int]) – The parameters to adjust the viewport to.

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.

Return type:

bool

class mokr.browser.WebWorker(client: mokr.connection.DevtoolsConnection, url: str, console_api_callback: Callable, exception_thrown: Callable)

Bases: pyee.EventEmitter

Represents a web worker on the page. This object is created and destroyed by it’s parent mokr.browser.Page.

Parameters:
  • client (DevtoolsConnection) – A mokr.connection.DevtoolsConnection spawned by the parent mokr.browser.Page.

  • url (str) – The “url” present in the triggering event’s “targetInfo”.

  • console_api_callback (Callable) – 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.

  • exception_thrown (Callable) – Callback to run if exception occurs.

property url: str

URL associated with the event that triggered this worker.

async execution_context() mokr.execution.context.ExecutionContext

Return the newly created mokr.execution.ExecutionContext.

Returns:

mokr.execution.ExecutionContext.

Return type:

ExecutionContext

async evaluate(page_function: str, *args: Any) dict | None

Execute a JavaScript function with given arguments. Run this WebWorker’s mokr.execution.ExecutionContext.evaluate.

Parameters:

page_function (str) – JavaScript function to run.

Raises:
Returns:

The decoded object (dict) via

mokr.execution.JavascriptHandle.json or None if a known error occurs decoding it.

Return type:

dict | None

async evaluate_handle(page_function: str, *args: Any) mokr.execution.context.JavascriptHandle

Execute a JavaScript function with given arguments. Run this WebWorker’s mokr.execution.ExecutionContext.evaluate_handle.

Parameters:

page_function (str) – JavaScript function to run.

Returns:

mokr.execution.JavascriptHandle.

Return type:

JavascriptHandle