mokr

Submodules

Attributes

BROWSER_CLOSE

MOKR_VERSION

TARGET_GET_CONTEXTS

version

version_info

Classes

Browser

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

Connection

Create remote connection.

ChromeLauncher

Class to handle launching browser process and creation of a

FirefoxLauncher

Class to handle launching browser process and creation of a

Functions

get_ws_endpoint(→ str)

Get the websocket URL for the remote browser at url.

launch(→ browser.Browser)

Launch a browser process and create a mokr.browser.Browser.

connect(→ browser.Browser)

Connect to an existing running browser.

Package Contents

class mokr.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.Connection(url: str, loop: asyncio.AbstractEventLoop, delay: int = 0)

Bases: pyee.EventEmitter, mokr.connection.base.RemoteConnection

Create remote connection.

Parameters:
  • url (str) – Websocket URL for remote connection.

  • loop (asyncio.AbstractEventLoop) – Running asyncio loop.

  • delay (int, optional) – Time in milliseconds to wait before handling messages. Defaults to 0.

connection: mokr.connection.devtools.DevtoolsConnection = None
property url: str

Get remote websocket URL.

send(method: str, params: dict = None) Awaitable[dict]

Send message to remote connection via websocket.

Parameters:
  • method (str) – Method to run.

  • params (dict, optional) – Arguments for method, if any. Defaults to None.

Raises:

ConnectionError – Raised if the connection is closed.

Returns:

Remote response as dictionary.

Return type:

Awaitable[dict]

async dispose() None

Sever all connections.

async create_session(target_info: dict) mokr.connection.devtools.DevtoolsConnection

Create a new mokr.connection.DevtoolsConnection.

Parameters:

target_info (dict) – Target info from triggered event.

Returns:

New DevtoolsConnection.

Return type:

DevtoolsConnection

mokr.BROWSER_CLOSE = 'Browser.close'
mokr.MOKR_VERSION = '0.2.0'
mokr.TARGET_GET_CONTEXTS = 'Target.getBrowserContexts'
class mokr.ChromeLauncher(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)

Bases: mokr.launch.base.Launcher

Class to handle launching browser process and creation of a mokr.browser.Browser object.

Parameters:
  • 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.launch import ChromeLauncher, FirefoxLauncher

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

# Or, to avoid the contextmanager.
launcher = FirefoxLauncher()
browser = await launcher.launch()
page = await browser.first_page()
await page.goto("https://example.com")
await launcher.stop()
```
kind = 'chrome'
class mokr.FirefoxLauncher(*args, **kwargs)

Bases: mokr.launch.base.Launcher

Class to handle launching browser process and creation of a mokr.browser.Browser object.

Parameters:
  • 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.launch import ChromeLauncher, FirefoxLauncher

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

# Or, to avoid the contextmanager.
launcher = FirefoxLauncher()
browser = await launcher.launch()
page = await browser.first_page()
await page.goto("https://example.com")
await launcher.stop()
```
kind = 'firefox'
async launch() mokr.browser.browser.Browser

Start browser process and return a mokr.browser.Browser object.

mokr.get_ws_endpoint(url) str

Get the websocket URL for the remote browser at url.

Parameters:

url (_type_) – Remote browser URL.

Raises:

BrowserError – Raised if browser closes while trying to resolve.

Returns:

Websocket URL from <url>/json/version response.

Return type:

str

mokr.version = '0.2.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) browser.Browser

Launch a browser process and create a mokr.browser.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:

A newly created mokr.browser.Browser instance.

Return type:

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

Connect to an existing running browser.

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

  • browser_ws_endpoint (str, optional) – An existing browser websocket endpoint to connect to. Should be formated like "ws://${host}:${port}/devtools/browser/<id>". Defaults to None, if not given, must give browser_url.

  • browser_url (str, optional) – An existing browser URL to connect to and get the websocket URL from. Should follow format of “http://${host}:${port}”. Defaults to None, if not given, must give browser_ws_endpoint.

  • 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 newly created mokr.browser.Browser instance.

Return type:

Browser