mokr.browser
Submodules
Classes
This class is created upon connect to a browser. It is essentially a |
|
Representation of console messages, dispatched on |
|
Browser context within the browser process. Contexts are independent |
|
Representative of a single tab within the browser (more specifically, |
|
Representative of a remote target. |
|
Handler for adjusting the browser viewport. Can adjust size and |
|
Represents a web worker on the page. This object is created and |
Package Contents
- 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.EventEmitterThis 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.BrowserContextinstances attached to this browser. By default, this will be a single context.
- property ws_endpoint: str
The websocket URL that this
Browser’smokr.connection.Connectionobject 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
Browserclass.- Return type:
- 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_pageinstead.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:
- async new_page() mokr.browser.page.Page
Spawn a new page within the default context.
- Returns:
A new
mokr.browser.Pageat “about:blank”.- Return type:
- targets() list[mokr.browser.target.Target]
A list of all
mokr.browser.Target`s in all contexts attached to this `Browserobject.- 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 `Browserobject.- Returns:
All pages within all contexts in this browser.
- Return type:
list[Page]
- async close() None
Run the
close_callbackgiven during initialisation.
- async disconnect() None
Disconnect the
Browser’sConnectionobject’s websocket connection and fail anyBrowser.targetsthat haven’t finished initialising.
- class mokr.browser.ConsoleMessage(kind: str, text: str, args: list[mokr.execution.JavascriptHandle] = None)
Representation of console messages, dispatched on
consoleevent inmokr.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.EventEmitterBrowser context within the browser process. Contexts are independent of one another, not sharing storage. Contexts beyond the default context that
mokr.browser.Browserstarts with will be incognito.- Parameters:
browser (Browser) – Parent
mokr.browser.Browserobject 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.Browserobject is spawned is not incognito.
- property browser: mokr.browser.Browser
The
mokr.browser.Browserobject 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.Pageat “about:blank”.- Return type:
- 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.EventEmitterRepresentative 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.
Pageemits events, often “inherited” from other classes (emitted in series on recieving them from bound classes); these events can be listened on viaPage.on. Note, however, that certain network events will be bound directly to thisPage’smokr.network.NetworkManagerwhen passed toPage.on. Additionally,Page.on("request")will not behaviour as a regular listener, but instead be added to the request interception callback chain. SeePage.onfor 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.
- 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:
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
Pagewith necessary remote configuration enabled.- Return type:
- property target: mokr.browser.target.Target
Parent
mokr.browser.TargetthisPagewas spawned from.
- property browser: mokr.browser.Browser
Parent
mokr.browser.BrowserthisPagebelongs to.
- property main_frame: mokr.frame.Frame | None
This
Page’smokr.frame.FrameManager’s mainmokr.frame.Frame.
- property network_manager: mokr.network.NetworkManager | None
This
Page’smokr.network.NetworkManager.
- property fetch_domain: mokr.network.FetchDomain
This
Page’smokr.fetch.FetchDomain.
- property http_domain: mokr.network.HttpDomain
This
Page’smokr.network.HttpDomain.
- property keyboard: mokr.input.Keyboard
This
Page’smokr.input.Keyboard.
- property mouse: mokr.input.Mouse
This
Page’smokr.input.Mouse.
- property touchscreen: mokr.input.Touchscreen
This
Page’smokr.input.Touchscreen.
- property frames: list[mokr.frame.Frame]
List of all
mokr.frame.Frameswithin thisPage.
- property workers: list[mokr.browser.worker.WebWorker]
List of all
mokr.browser.WebWorker`s within this `Page.
- property url: str
The URL the
Pageis 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
Pageis still alive, otherwise False. If a parentmokr.browser.BrowserContextis closed, all child `Page`s will close, too.
- property browser_type: str
One of “chrome” or “firefox”.
- on(event: str, method: Callable | None) None
Registers the callable
methodto the event nameevent, if provided. When the targeteventis emitted by this class, the targetmethodwill be called.Notably, the event “request” does not register a listener. Instead, it adds the method to this
Page’smokr.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.RequestisRequest.released,.aborted, or.fulfilled. For request interception, methods are executed in reverse order of registration, so newerPage.onmethods 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.HttpDomainbound to this page.This method does not ever need to be called directly; accessing
Page.http_domainwill 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_cookiesto: - “both” (default): Sync back and forth. - “http”: Sync to theHttpDomainfrom thePageonly. - “page”: Sync to thePagefrom theHttpDomainonly. - “none”: Don’t sync at all.- Parameters:
sync_cookies (Literal["both", "http", "page", "none"], optional) – Whether to sync cookies between the
HttpDomainand the parentPagebefore/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.onfor 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 forPage.main_frame.tap.This method is a shortcut for running
Page.query_selectorand then runningmokr.execution.ElementHandle.tapon 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 boundPage.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.
Change the default navigation timeout. This is used by
Page.goto,Page.go_back,Page.go_forward,Page.wait_for_navigation,Page.refresh, andPage.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 defaultmokr.frame.Frame.evaluate_handle.- Parameters:
page_function (str) – JavaScript function to run.
- Raises:
PageError – Raised if the
Page’s mainmokr.frame.Framefails to find itsmokr.browser.ExecutionContext.- Returns:
mokr.execution.JavascriptHandle.- Return type:
- async query_objects(javascript_handle: mokr.execution.JavascriptHandle) mokr.execution.JavascriptHandle
Query all objects with the given
mokr.execution.JavascriptHandle’sget_property("objectId"). Wrapper for thisPage.main_frame’smokr.execution.ExecutionContext.query_objects.- Parameters:
javascript_handle (JavascriptHandle) – A valid (not disposed)
mokr.execution.JavascriptHandleobject.- Raises:
PageError – Raised if the
Page’s mainmokr.frame.Framefails to find itsmokr.browser.ExecutionContext.ElementHandleError – Raised if the given handle is disposed, or does not have an “objectId” remote property (primitive type).
- Returns:
- A
mokr.execution.JavascriptHandleinitialised from the remot response.
- A
- Return type:
- 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 forPage.main_frame.embed_javascript.- Parameters:
file_content (str, optional) – Encoded file content for script to embed. If not given, must give
file_pathorurl. Defaults to None.file_path (str, optional) – File path for script to embed. If not given, must give
file_contentorurl. Defaults to None.url (str, optional) – URL for script to embed. If not given, must give
file_contentorfile_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, orurlare given.PageError – Raised if error occurs sending embed request to remote connection (from ElementHandleError).
- Returns:
Newly embedded element.
- Return type:
- 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 forPage.main_frame.embed_style.- Parameters:
file_content (str, optional) – Encoded file content for style to embed. If not given, must give
file_pathorurl. Defaults to None.file_path (str, optional) – File path for style to embed. If not given, must give
file_contentorurl. Defaults to None.url (str, optional) – URL for style to embed. If not given, must give
file_contentorfile_path. Defaults to None.
- Raises:
ValueError – Raised if none of
file_content,file_path, orurlare given.PageError – Raised if error occurs sending embed request to remote connection (from ElementHandleError).
- Returns:
Newly embedded element.
- Return type:
- async expose_function(name: str, method: Callable) None
Bind a remote JavaScript function “name” to local
method. This will allow triggering localmethodby callingwindow["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 forPage.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 forPage.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.onfor 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_untilevent. 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_untilevents 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_untilevent. 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_untilevent. 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_untilevent. 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_untilevents are recieved.- Returns:
Last response recieved after all redirects, if any.
- Return type:
Response | None
Wait for navigation to occur. Navigation is triggered by
Page.goto,Page.refresh, redirects, and history (Page.go_backandPage.go_forward).Note that anchor navigation will not and history navigation may not yield any
mokr.network.Responseobjects.- Parameters:
timeout (int | None, optional) – Time in milliseconds to wait for
wait_untilevent. 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_untilevents 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.Requestwhoseurlmatches theurlor that evaluates to True when passed tomethod.- 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_managerto. Defaults to None.timeout (int | None, optional) – Time in milliseconds to wait. Defaults to 30000.
- Raises:
ValueError – Raised if neither
urlnormethodgiven.- Returns:
First matching
mokr.network.Request.- Return type:
- async wait_for_response(url: str | None = None, method: Callable | None = None, timeout: int | None = 30000) mokr.network.Response
Wait for a
mokr.network.Responsewhoseurlmatches theurlor that evaluates to True when passed tomethod.- 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_managerto. Defaults to None.timeout (int | None, optional) – Time in milliseconds to wait. Defaults to 30000.
- Raises:
ValueError – Raised if neither
urlnormethodgiven.- Returns:
First matching
mokr.network.Response.- Return type:
- async bring_to_front() None
Bring this
Pageto 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
viewportparameters. 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 defaultmokr.frame.Frame.evaluate.- Parameters:
page_function (str) – JavaScript function to run.
force_expr (bool) – If True, treat
page_functionas an expression. Otherwise, automatically determine if it is a function or an expression. Defaults to False.
- Raises:
either evaluating the function or requesting the resulting object. –
- Returns:
- The decoded object (dict) via
mokr.execution.JavascriptHandle.jsonor 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.Requestobjects.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_typeisn’t given and can’t be inferred as a supported type fromfile_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.pdfgenerates a pdf of the page with “print” css media. To generate a pdf with screen media, first callpage.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_templatebut 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
widthandheight. Defaults to None.prefer_css_page_size (bool, optional) – Any CSS “@page” size. Overrides values from
paper_format,width, andheight. 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 forPage.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 forPage.main_frame.click.This method is a shortcut for running
Page.query_selectorand then runningmokr.execution.ElementHandle.clickon the resultant ElementHandle. In either case, an element will be scrolled into view if needed, and the center of it clicked with the boundPage.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 forPage.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 forPage.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
selectorand type characters into it. Wrapper forPage.main_frame.type_text.Note that modifier keys do not alter text case, meaning sending
mokr.input.Keyboard.press("shift")and typingPage.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 forPage.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
selectorto appear in DOM. If element is in DOM already when called, return immediately. Wrapper forPage.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.ElementHandlefrom 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
xpathexpression to appear in DOM. If element is in DOM already when called, return immediately. Wrapper forPage.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.ElementHandlefrom 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_functionreturns a truthy value. Wrapper forPage.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_functionsuccessful 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
requestis 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, andheadersfrom. 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
urlnorrequestgiven.NetworkError – Raised if no response found when request resolves.
- Returns:
Last response recieved after all redirects, if any.
- Return type:
- 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
dataorjsonarguments given with incompatible methods.- Returns:
- A
mokr.network.Responsecreated from the httpx.Response. All redirects will also be created, and original requests and responses will be accessible from themokr.networkobjects.
- A
- Return type:
- 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.ccat 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.BrowserContextthat this spawned from.session_factory (Callable) – Callable that creates a new
mokr.connection.DevtoolsConnectionfor 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
asyncioloop that is tracked under themokr.browser.Browser’smokr.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.Browserthat owns themokr.browser.BrowserContextthat this target was initialised from.
- property browser_context: mokr.browser.context.BrowserContext
mokr.browser.BrowserContextthis target was initialised from.
- async create_devtools_connection() mokr.connection.DevtoolsConnection
Initialise the
mokr.connection.DevtoolsConnectionthat will be bound to thisTarget.- Returns:
The new
mokr.connection.DevtoolsConnection.- Return type:
- async page() mokr.browser.page.Page | None
Get the
mokr.browser.Pageobject attached to thisTarget. Only applicable ifTarget.kindis “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.DevtoolsConnectionobject, shared from the parentmokr.browser.Page.
- async emulate_viewport(viewport: dict[str, bool | int]) bool
Run viewport adjustments based off given
viewportparameters. 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
viewportare 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.EventEmitterRepresents 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.DevtoolsConnectionspawned by the parentmokr.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 parentPage.exception_thrown (Callable) – Callback to run if exception occurs.
- console_api_callback
- 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:
- async evaluate(page_function: str, *args: Any) dict | None
Execute a JavaScript function with given arguments. Run this
WebWorker’smokr.execution.ExecutionContext.evaluate.- Parameters:
page_function (str) – JavaScript function to run.
- Raises:
either evaluating the function or requesting the resulting object. –
- Returns:
- The decoded object (dict) via
mokr.execution.JavascriptHandle.jsonor 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’smokr.execution.ExecutionContext.evaluate_handle.- Parameters:
page_function (str) – JavaScript function to run.
- Returns:
mokr.execution.JavascriptHandle.- Return type: