mokr.browser.page

Module Contents

Classes

Page

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

Attributes

LOGGER

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