Target

class selenium_driverless.types.target.Target(host, target_id, driver, context, is_remote=False, loop=None, timeout=30, type=None, start_socket=False, max_ws_size=1048576)[source]

the Target class

Usually a tab, (cors-)iframe, WebWorker etc.

property socket: SingleCDPSocket

the cdp-socket for the connection

async get_targets_for_iframes(iframes)[source]

find targets for a list of iframes

Parameters:

iframes (List[WebElement]) – iframes to find targets for

Warning

only CORS iframes have its own target, you might use WebElement.content_document instead

async get_target_for_iframe(iframe)[source]

find a target for an iframe

Parameters:

iframe (WebElement) – iframe to find target for

Warning

only CORS iframes have its own target, you might use WebElement.content_document instead

async wait_download(timeout=30)[source]

wait for a download on the current tab

returns something like

{
    "frameId": "2D543B5E8B14945B280C537A4882A695",
    "guid": "c91df4d5-9b45-4962-84df-3749bd3f926d",
    "url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "suggestedFilename": "dummy.pdf",

    # only if options.downloads_dir specified
    "guid_file": "D:\System\AppData\PyCharm\scratches\downloads\c91df4d5-9b45-4962-84df-3749bd3f926d"
}
Parameters:

timeout (float) – time in seconds to wait for a download

Return type:

dict

Warning

downloads from iframes not supported yet

async get(url, referrer=None, wait_load=True, timeout=30)[source]

Loads a web page

Parameters:
  • url (str) – the url to load.

  • referrer (Optional[str]) – the referrer to load the page with

  • wait_load (bool) – whether to wait for the webpage to load

  • timeout (float) – the maximum time in seconds for waiting on load

Return type:

dict

returns the same as Target.wait_download if the url initiates a download

property pointer: Pointer

the Pointer for this target

async send_keys(text, allow_not_on_mapping=True)[source]

send text & keys to the target

Parameters:
  • text (str) – the text to send to the target

  • allow_not_on_mapping (bool) – allow keys which aren’t int the keyboard mapping

async execute_raw_script(script, *args, await_res=False, serialization=None, max_depth=None, timeout=2, execution_context_id=None, unique_context=False)[source]

executes a JavaScript on GlobalThis such as

function(...arguments){return document}

this and obj refers to globalThis (=> window) here

Parameters:
  • script (str) – the script as a string

  • args – the argument which are passed to the function. Those can be either json-serializable or a RemoteObject such as WebELement

  • await_res (bool) – whether to await the function or the return value of it

  • serialization (Optional[str]) – can be one of deep, json, idOnly

  • max_depth (Optional[int]) – The maximum depth objects get serialized.

  • timeout (float) – the maximum time to wait for the execution to complete

  • execution_context_id (Optional[str]) – the execution context id to run the JavaScript in. Exclusive with unique_context

  • unique_context (bool) – whether to use a isolated context to run the Script in.

see Runtime.callFunctionOn

async execute_script(script, *args, max_depth=2, serialization=None, timeout=None, execution_context_id=None, unique_context=None)[source]

executes JavaScript synchronously on GlobalThis such as

return document

this and obj refers to globalThis (=> window) here

see Target.execute_raw_script for argument descriptions

async execute_async_script(script, *args, max_depth=2, serialization=None, timeout=None, execution_context_id=None, unique_context=None)[source]

executes JavaScript asynchronously on GlobalThis

resolve = arguments[arguments.length-1]

this and obj refers to globalThis (=> window) here

see Target.execute_raw_script for argument descriptions

async eval_async(script, *args, max_depth=2, serialization=None, timeout=None, execution_context_id=None, unique_context=None)[source]

executes JavaScript asynchronously on GlobalThis such as

res = await fetch("https://httpbin.org/get");
// mind CORS!
json = await res.json()
return json

this refers to globalThis (=> window)

see Target.execute_raw_script for argument descriptions

property current_url: str

Gets the URL of the current page.

Usage:
target.current_url
property page_source: str

Gets the HTML of the current page.

async close(timeout=2)[source]

Closes the current window.

Usage:
target.close()
Return type:

None

async focus(activate=False)[source]

emulates Focus of the target

Parameters:

activate – whether to bring the window to the front

async unfocus()[source]

disables focus emulation for the target

async activate()[source]

brings the window to the front

property title: str

Returns the title of the target

async print_page()[source]

Takes PDF of the current page.

The target makes the best effort to return a PDF based on the provided parameters.

returns Base64-encoded pdf data as a string

Return type:

str

async get_history()[source]

returns the history data

see Page.getNavigationHistory

Return type:

NavigationHistory

async back()[source]

Goes one step backward in the browser history.

Return type:

None

async forward()[source]

Goes one step forward in the browser history.

Return type:

None

async refresh()[source]

Refreshes the page.

Return type:

None

async get_cookies()[source]

Returns a set of dictionaries, corresponding to cookies visible in the current context.

Return type:

List[dict]

Get a single cookie by name. Returns the cookie if found, None if not.

Return type:

Optional[Dict]

Deletes a single cookie with the given name.

Return type:

None

async delete_all_cookies()[source]

Delete all cookies in the scope of the context.

Return type:

None

Adds a cookie in the current (incognito-) context

Parameters:

cookie_dict – see Network.CookieParam

Return type:

None

async find_element(by, value, timeout=None)[source]

find an element in the current target

Parameters:
  • by (str) – one of the locators at By

  • value (str) – the actual query to find the element by

  • timeout (Optional[int]) – how long to wait for the element to exist

Return type:

WebElement

async find_elements(by, value)[source]

find multiple elements in the current target

Parameters:
  • by (str) – one of the locators at By

  • value (str) – the actual query to find the elements by

Return type:

List[WebElement]

async set_source(source, timeout=15)[source]

sets the OuterHtml of the current target (if it has DOM//HTML)

Parameters:
  • source (str) – the html

  • timeout (float) – the timeout to try setting the source (might fail if the page is in a reload-loop

async search_elements(query)[source]

query:str | Plain text or query selector or XPath search query.

Return type:

List[WebElement]

async get_screenshot_as_file(filename)[source]

Saves a screenshot of the current window to a PNG image file.

Parameters:

filename (str) – The full path. This should end with a .png extension.

Return type:

None

async save_screenshot(filename)[source]

alias to :func: driver.get_screenshot_as_file <selenium_driverless.webdriver.Chrome.get_screenshot_as_file>

Return type:

None

async get_screenshot_as_png()[source]

Gets the screenshot of the current window as a binary data.

Return type:

bytes

async snapshot()[source]

gets the current snapshot as mhtml

Return type:

str

async save_snapshot(filename)[source]

Saves a snapshot of the current window to a MHTML file.

Parameters:

filename (str) – The full path you wish to save your snapshot to. This should end with a .mhtml extension.

await driver.get_snapshot('snapshot.mhtml')
async get_network_conditions()[source]

Gets Chromium network emulation settings.

Returns:

A dict. For example: {‘latency’: 4, ‘download_throughput’: 2, ‘upload_throughput’: 2, ‘offline’: False}

async set_network_conditions(offline, latency, download_throughput, upload_throughput, connection_type)[source]

Sets Chromium network emulation settings.

Args:
  • network_conditions: A dict with conditions specification.

Usage:
target.set_network_conditions(
    offline=False,
    latency=5,  # additional latency (ms)
    download_throughput=500 * 1024,  # maximal throughput
    upload_throughput=500 * 1024,  # maximal throughput
    connection_type="wifi")

Note: ‘throughput’ can be used to set both (for download and upload).

Return type:

None

async delete_network_conditions()[source]

Resets Chromium network emulation settings.

Return type:

None

async wait_for_cdp(event, timeout=None)[source]

wait for a CDP event and return the data :type event: str :param event: the name of the event :type timeout: Optional[float] :param timeout: timeout to wait in seconds.

Return type:

dict

async add_cdp_listener(event, callback)[source]

add a listener on a CDP event (current target)

Parameters:
  • event (str) – the name of the event

  • callback (Callable[[dict], any]) – the callback on the event

Note

callback has to accept one parameter (event data as json)

async remove_cdp_listener(event, callback)[source]

removes the CDP listener :type event: str :param event: the name of the event :type callback: Callable[[dict], any] :param callback: the callback to remove

async get_cdp_event_iter(event)[source]

iterate over a cdp event

Parameters:

event (str) – name of the event to iterate over

Return type:

AsyncIterable[dict]

async for data in await target.get_cdp_event_iter("Page.frameNavigated"):
    print(data["frame"]["url"]

Warning

async only supported for now

async execute_cdp_cmd(cmd, cmd_args=None, timeout=10)[source]

Execute Chrome Devtools Protocol command and get returned result The command and command args should follow chrome devtools protocol domains/commands, refer to link https://chromedevtools.github.io/devtools-protocol/

Args:
  • cmd: A str, command name

  • cmd_args: A dict, command args. empty dict {} if there is no command args

Usage:
target.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})
Returns:

A dict, empty dict {} if there is no result to return. For example to getResponseBody: {‘base64Encoded’: False, ‘body’: ‘response body string’}

Return type:

dict

async fetch(url, method='GET', headers=None, body=None, mode=None, credentials=None, cache=None, redirect=None, referrer=None, referrer_policy=None, integrity=None, keepalive=None, priority='high', timeout=20)[source]

executes a JS fetch request within the target, see developer.mozilla.org/en-US/docs/Web/API/fetch for reference

returns smth like

{
    "body":bytes,
    "headers":dict,
    "ok":bool,
    "status_code":int,
    "redirected":bool,
    "status_text":str,
    "type":str,
    "url":str
}
Return type:

dict

async xhr(url, method='GET', user=None, password=None, with_credentials=True, mime_type='text/plain', extra_headers=None, timeout=30)[source]

executes a JS XMLHttpRequest request within the target, see developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest for reference

Parameters:
  • url (str) – the url to get

  • method (Literal['GET', 'POST', 'PUT', 'DELETE']) – one of “GET”, “POST”, “PUT”, “DELETE”

  • user (Optional[str]) – user to authenticate with

  • password (Optional[str]) – password to authenticate with

  • with_credentials (bool) – whether to include cookies

  • mime_type (str) – the type to parse the response as

  • extra_headers (Optional[Dict[str, str]]) – a key/value dict of extra headers to add to the request

  • timeout (float) – timeout in seconds for the request to take

Return type:

dict

returns smth like

{
    "status": int,
    "response": any,
    "responseText":str,
    "responseType":str,
    "responseURL":str,
    "responseXML":any,
    "statusText":str,
    "responseHeaders":dict
}
async get_sinks()[source]
Returns:

A list of sinks available for Cast.

Return type:

list

async get_issue_message()[source]
Returns:

An error message when there is any issue in a Cast session.

async set_sink_to_use(sink_name)[source]

Sets a specific sink, using its name, as a Cast session receiver target.

Args:
  • sink_name: Name of the sink to use as the target.

Return type:

dict

async start_desktop_mirroring(sink_name)[source]

Starts a desktop mirroring session on a specific receiver target.

Args:
  • sink_name: Name of the sink to use as the target.

Return type:

dict

async start_tab_mirroring(sink_name)[source]

Starts a tab mirroring session on a specific receiver target.

Parameters:

sink_name (str) – Name of the sink to use as the target.

Return type:

dict

async stop_casting(sink_name)[source]

Stops the existing Cast session on a specific receiver target.

Parameters:

sink_name (str) – Name of the sink to stop the Cast session.

Return type:

dict

class selenium_driverless.types.target.TargetInfo(target_info, target_getter)[source]

Info for a Target

Note

the infos are not dynamic

property Target: Target

the Target itself

property id: str

the Target.TargetID

property attached: str

Whether the target has an attached client.

property opener_id: str

Opener Target.TargetId

property can_access_opener

Whether the target has access to the originating window.

property opener_frame_id

Page.FrameId of originating window (is only set if target has an opener).

property browser_context_id

Browser.BrowserContextID

property subtype

Provides additional details for specific target types. For example, for the type of “page”, this may be set to “portal” or “prerender

class selenium_driverless.types.base_target.BaseTarget(host, is_remote=False, loop=None, timeout=30, max_ws_size=1048576)[source]

the baseTarget for the ChromeInstance represents a connection to the whole browser.

Note

commands executed on BaseTarget usually are on a global scope over the whole Chrome instance. unfortunately, not all are supported

property socket: SingleCDPSocket

the cdp-socket for the connection

async wait_for_cdp(event, timeout=None)[source]

wait for an event see Target.wait_for_cdp for reference

async add_cdp_listener(event, callback)[source]

add a listener for a CDP event see Target.add_cdp_listener for reference

async remove_cdp_listener(event, callback)[source]

remove a listener for a CDP event see Target.remove_cdp_listener for reference

async get_cdp_event_iter(event)[source]

iterate over CDP events on the current target see Target.get_cdp_event_iter for reference

Return type:

AsyncIterable[dict]

async execute_cdp_cmd(cmd, cmd_args=None, timeout=10)[source]

Execute Chrome Devtools Protocol command and get returned result see Target.execute_cdp_cmd for reference

Return type:

dict

downloads_dir_for_context(context_id='DEFAULT')[source]

get the default download directory for a specific context

Parameters:

context_id (str) – the id of the context to get the directory for

Return type:

str