mokr

Submodules

Attributes

version

version_info

Classes

Browser

BrowserContext

Connection

The event-capable command transport shared by CDP and BiDi.

Element

Portable DOM-element operations shared by browser backends.

Frame

Portable frame operations shared by browser backends.

Page

Portable page operations returned by mokr.launch().

Request

Portable request interception operations.

Response

Portable response metadata and body access.

Functions

launch(→ launch.Launcher[protocols.Browser])

Launch a browser process and create a browser matching Browser.

connect(→ protocols.Browser)

Connect to an existing running browser.

Package Contents

class mokr.Browser(browser_type: str, *args: Any, close_callback: Callable | None = None, default_viewport: dict[str, Any] | None = None, default_user_agent: str | None = None, **kwargs: Any)

Bases: Protocol

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

  • 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

The active browser backend kind.

property process: Any

The local browser process, if this browser was launched locally.

property browser_contexts: list[mokr.protocols.context.BrowserContext]

The default and isolated browser contexts.

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

Return the default context’s first page, if present.

async new_page() mokr.protocols.page.Page

Create and return a page in the default browser context.

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

Return all open pages across contexts.

async create_incognito_browser_context() mokr.protocols.context.BrowserContext

Create and return an isolated browser context.

async close() None

Close the browser.

async disconnect() None

Disconnect without requesting browser shutdown.

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

Bases: Protocol

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

Whether this is an isolated non-default context.

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

Return pages in this context.

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

Return this context’s first page, if present.

async new_page() mokr.protocols.page.Page

Create and return a page in this context.

async close() None

Close this browser context.

class mokr.Connection

Bases: Protocol

The event-capable command transport shared by CDP and BiDi.

property url: str

The transport WebSocket URL.

property loop: asyncio.AbstractEventLoop

The event loop used by the transport.

on(event: str, listener: collections.abc.Callable[Ellipsis, Any]) Any

Register a listener for a protocol event.

remove_listener(event: str, listener: collections.abc.Callable[Ellipsis, Any]) Any

Remove a previously registered protocol-event listener.

async send(method: str, params: dict[str, Any] | None = None) Any

Send a protocol command and return its result.

async dispose() None

Close the protocol transport and release resources.

class mokr.Element

Bases: Protocol

Portable DOM-element operations shared by browser backends.

async click() None

Click this element.

async content() str

Return this element’s serialized HTML.

async bounding_box() dict[str, float] | None

Return this element’s viewport bounding box, if attached.

class mokr.Frame

Bases: Protocol

Portable frame operations shared by browser backends.

property url: str

The frame’s current URL.

async evaluate(page_function: str, *args: Any) Any

Evaluate JavaScript in this frame with JSON-like arguments.

async query_selector(selector: str) mokr.protocols.element.Element | None

Return the first element matching a CSS selector, if any.

async query_selector_all(selector: str) list[mokr.protocols.element.Element]

Return all elements matching a CSS selector.

class mokr.Page

Bases: Protocol

Portable page operations returned by mokr.launch().

property url: str

The page’s current URL.

property is_closed: bool

Whether the page has been closed.

on(event: str, listener: collections.abc.Callable[Ellipsis, Any]) Any

Register an event listener or request-interception callback.

async goto(url: str, timeout: int | None = None, wait_until: str = 'load') Any

Navigate to a URL and wait for the requested readiness state.

async content() str

Return the current document’s serialized HTML.

async set_content(html: str) None

Replace the current document’s HTML.

async evaluate(page_function: str, *args: Any) Any

Evaluate JavaScript in this page with JSON-like arguments.

async screenshot(**kwargs: Any) bytes | str

Capture a screenshot of the page.

async close(run_before_unload: bool = False) None

Close the page.

class mokr.Request

Bases: Protocol

Portable request interception operations.

property url: str

The intercepted request URL.

property method: str

The intercepted HTTP method.

property headers: dict[str, str]

Request headers, keyed case-insensitively in lowercase.

async release() None

Continue the intercepted request unchanged.

async abort() None

Fail the intercepted request.

async fulfill(body: str | bytes = b'', status: int = 200, headers: dict[str, str] | None = None) None

Fulfill the intercepted request with a synthetic response.

class mokr.Response

Bases: Protocol

Portable response metadata and body access.

property url: str

The response URL.

property status: int

The HTTP status code.

property ok: bool

Whether the response has a non-error HTTP status.

property reason: str

The HTTP reason text.

property headers: dict[str, str]

Response headers, keyed case-insensitively in lowercase.

async buffer() bytes

Return the response body as bytes.

async content() str

Return the response body decoded as text.

async json() Any

Decode the response body as JSON.

async to_dict() dict[str, Any]

Return the response status, headers, and decoded body.

mokr.version = '1.0.0'
mokr.version_info
mokr.launch(browser_type: Literal['chrome', 'firefox'] = 'chrome', binary_path: str = None, headless: bool = None, user_data_dir: str = None, devtools: bool = False, ignore_default_args: bool | list[str] = False, ignore_https_errors: bool = False, default_viewport: dict[str, int] = None, proxy: str = None, default_user_agent: str = None, slow_mo: int = 0, log_level: str | int = None, args: list[str] = None, dumpio: bool = False, env: dict[str, str] = None, loop: asyncio.AbstractEventLoop = None, firefox_user_prefs: dict = None, firefox_addons_paths: list[str] = None) launch.Launcher[protocols.Browser]

Launch a browser process and create a browser matching Browser. Wrapper for mokr.launch.Launcher.launch.

Parameters:
  • browser_type (Literal["chrome", "firefox"]) – The type of browser to, use. One of “chrome” or “firefox”. Note that Firefox is not fully implemented and only offers partial functionality.

  • binary_path (str, optional) – Path to executable to use. Defaults to None (looks for default executable that can be installed via mokr install).

  • headless (bool, optional) – Run the browser in headless (no window) mode. Defaults to None (uses opposite value to devtools).

  • user_data_dir (str, optional) – Path to a user data directory. Defaults to None.

  • devtools (bool, optional) – Automatically open the developer tools panel. Defaults to False.

  • ignore_default_args (bool | list[str], optional) – Either a bool to indicate ignoring all arguments or a list of arguments to ignore. Be cautious, ignoring some arguments may cause unexpected results. Defaults to False.

  • ignore_https_errors (bool, optional) – Ignore site security errors. Defaults to False.

  • default_viewport (dict[str, int], optional) – Set the default viewport for new pages. Accepts a dictionary keyed with viewport options. Not all viewport options are considered, only: “isMobile”, “width”, “height”, “deviceScaleFactor”, “isLandscape”, and “hasTouch”. Defaults to None (800x600 viewport).

  • proxy (str, optional) – Proxy to route all requests through. Can be a regular HTTP/S proxy or SOCKS proxy. Expects proxy as <scheme>://[(optional)<username>:<password>]@<host><password>.

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

  • slow_mo (int, optional) – Slow execution of remote calls by the given time in milliseconds. Defaults to 0.

  • log_level (str | int, optional) – Log level to log at. Defaults to None (same as root).

  • args (list[str], optional) – Additional arguments to pass to the browser process when launching. Defaults to None.

  • dumpio (bool, optional) – Pipe the browser process’ stdout and stderr into process.stdout and process.stderr. Defaults to False.

  • env (dict[str, str], optional) – Additional environment variables that the browser process will be able to read. Defaults to None.

  • loop (asyncio.AbstractEventLoop, optional) – A running asyncio loop to execute within. Defaults to None (uses asyncio.get_event_loop).

  • firefox_user_prefs (dict) – Firefox only. User preferences to load.

  • firefox_addons_paths (list[str]) – Firefox only. A list of paths to addons that will be installed as temporary extensions.

Example:

```python
from mokr import launch

async with launch() as browser:
    page = await browser.first_page()
    await page.goto("https://example.com")

# Or, to avoid the contextmanager.
launcher = launch()
browser = await launcher.launch()
page = await browser.first_page()
await page.goto("https://example.com")
await launcher.stop()
```
Raises:

ValueError – Raised if browser_type isn’t of “chrome” or “firefox”.

Returns:

An async context manager that yields a browser backed by CDP for Chrome or BiDi for Firefox.

Return type:

Launcher[Browser]

async mokr.connect(browser_type: Literal['chrome', 'firefox'] = 'chrome', browser_ws_endpoint: str = None, browser_url: str = None, ignore_https_errors: bool = False, default_viewport: dict[str, int] = None, slow_mo: int = 0, log_level: str | int = None, loop: asyncio.AbstractEventLoop = None) protocols.Browser

Connect to an existing running browser.

Parameters:
  • browser_type (Literal["chrome", "firefox"]) – Chrome uses CDP; Firefox uses WebDriver BiDi.

  • browser_ws_endpoint (str, optional) – A CDP browser WebSocket for Chrome or BiDi WebSocket for Firefox.

  • browser_url (str, optional) – Chrome-only DevTools HTTP URL used to discover the browser WebSocket.

  • ignore_https_errors (bool, optional) – Ignore site security errors. Defaults to False.

  • default_viewport (dict[str, int], optional) – Set the default viewport for new pages. Accepts a dictionary keyed with viewport options. Not all viewport options are considered, only: “isMobile”, “width”, “height”, “deviceScaleFactor”, “isLandscape”, and “hasTouch”. Defaults to None (800x600 viewport).

  • slow_mo (int, optional) – Slow execution of remote calls by the given time in milliseconds. Defaults to 0.

  • log_level (str | int, optional) – Log level to log at. Defaults to None (same as root).

  • loop (asyncio.AbstractEventLoop, optional) – A running asyncio loop to execute within. Defaults to None (uses asyncio.get_event_loop).

Raises:

ValueError – Raised if browser_type isn’t of “chrome” or “firefox” or neither browser_ws_endpoint nor browser_url are given.

Returns:

A connected browser facade.

Return type:

Browser