webdriver.Chrome

class selenium_driverless.webdriver.Chrome(options=None, timeout=30, debug=False, max_ws_size=134217728)[source]

Control the chromium based browsers without any driver.

property frame_tree: dict

async all nested frames within the current target

property targets: Dict[str, TargetInfo]

async all targets within the current context

property contexts: Dict[str, Context]

async all (incognito) contexts on Chrome.

async new_context(proxy_bypass_list=None, proxy_server=True, universal_access_origins=None, url='about:blank')[source]

creates a new (incognito) context

Parameters:
  • url (str) – the url the first tab will start at. “about:blank” by default

  • universal_access_origins (Optional[List[str]]) – An optional list of origins to grant unlimited cross-origin access to. Parts of the URL other than those constituting origin are ignored

Return type:

Context

Warning

The proxy parameter doesn’t work on Windows due to crbug#1310057.

Parameters:
  • proxy_server (str) – a proxy-server to use for the context

  • proxy_bypass_list (Optional[List[str]]) – a list of proxies to ignore

async get_targets(_type=None, context_id='self')[source]

get all targets within the current context :type _type: Optional[Literal['page', 'background_page', 'service_worker', 'browser', 'other']] :param _type: filter by target type :type context_id: str :param context_id: if None, this function returns all targets for all contexts.

Return type:

Dict[str, TargetInfo]

property current_target: Target

the current Target

property base_target: BaseTarget

The connection handle for the global connection to Chrome

Warning

only the bindings for using the CDP-protocol on BaseTarget supported

property mv3_extension: Target

async the target for the background script of the by default loaded Chrome-extension (manifest-version==3)

async ensure_extensions_incognito_allowed()[source]

ensure that all installed Chrome-extensions are allowed in incognito context.

Warning

Generally, the extension decides whether to use the split, spanning or not_allowed configuration. For changing this behaviour, you’ll have to modify the manifest.json file within the compressed extension or directory. See developer.chrome.com/docs/extensions/reference/manifest/incognito.

property base_context: Context

the Context which isn’t incognito

property downloads_dir

the current downloads directory for the current context

async set_download_behaviour(behaviour, path=None)[source]

set the download behaviour

Parameters:
  • behaviour (Literal['deny', 'allow', 'allowAndName', 'default']) – the behaviour to set the downloading to

  • path (Optional[str]) – the path to the default download directory

Warning

setting behaviour=allow instead of allowAndName can cause some bugs

property current_context: Context

the current context switched to

async get_target(target_id=None, timeout=2)[source]

get a Target by TargetId for advanced usage of the CDP protocol :type target_id: Optional[str] :param target_id: :type timeout: float :param timeout: timeout in seconds for connecting to the target if it’s not tracked already

Return type:

Target

async get_target_for_iframe(iframe)[source]

get the Target for a specific iframe

Warning

only cross-iframes have a Target due to OOPIF. See site-isolation For a general solution, have a look at WebElement.content_document instead

Parameters:

iframe (WebElement) – the iframe to get the Target for

Return type:

Target

async get_targets_for_iframes(iframes)[source]

returns a list of targets for iframes see webdriver.Chrome.get_target_for_iframe for more information

Parameters:

iframes (List[WebElement]) – the iframe to get the targets for

Return type:

List[Target]

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 in the current Target

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:

Optional[dict]

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

property title: str

async the title of the current target

property current_pointer: Pointer

the Pointer for this target

async send_keys(text)[source]

send text & keys to the current target

Parameters:

text (str) – the text to send

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

executes a JavaScript on GlobalThis such as

function(...arguments){return document}
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 (Literal['deep', 'json', 'idOnly']) – 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 – the execution context id to run the JavaScript in. Exclusive with unique_context

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

see Runtime.callFunctionOn

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

executes JavaScript synchronously on GlobalThis such as

return document

see Target.execute_raw_script for argument descriptions

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

executes JavaScript asynchronously on GlobalThis such as

Warning

using execute_async_script is not recommended as it doesn’t handle exceptions correctly. Use Chrome.eval_async

resolve = arguments[arguments.length-1]

see Target.execute_raw_script for argument descriptions

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

executes JavaScript asynchronously on GlobalThis such as

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

see Target.execute_raw_script for argument descriptions

property current_url: str

async current URL of the current Target

property page_source: str

async html of the current page.

async close(timeout=2)[source]

Closes the current target (only works for tabs). :type timeout: float :param timeout: timeout in seconds for the tab to close

Return type:

None

async focus()[source]

focuses the current target (only works for tabs)

async quit(timeout=30, clean_dirs=True)[source]

Closes Chrome :type timeout: float :param timeout: the maximum time waiting for chrome to quit correctly :type clean_dirs: bool :param clean_dirs: whether to clean out the user-data-dir directory

Return type:

None

property current_target_info: TargetInfo

async TargetInfo of the current target

property current_window_handle: str

current TargetId

Warning

this is deprecated and will be removed use webdriver.Chrome.current_target.id instead

property current_window_id

async the WindowId of the window the current Target belongs to

property window_handles: List[TargetInfo]

async TargetInfo on all tabs in the current context

Warning

the tabs aren’t ordered by position in the window. Do not rely on the index, but iterate and filter them.

async new_window(type_hint='tab', url='', activate=True)[source]

Creates a new window or tab in the current context

Parameters:
  • type_hint (Literal['tab', 'window']) – whether to create a tab or window

  • url – the url which the new window should start on. Defaults to about:blank

  • activate (bool) – whether to explicitly activate/focus the window

Return type:

Target

new_target = driver.new_window('tab')
async set_window_state(state)[source]

sets the window state on the window the current Target belongs to :type state: Literal['normal', 'minimized', 'maximized', 'fullscreen'] :param state: the state to set

async normalize_window()[source]

Normalizes the window position and size on the window the current Target belongs to

async maximize_window()[source]

Maximizes the window the current Target belongs to

Return type:

None

async fullscreen_window()[source]

enters fullscreen on the window the current Target belongs to

Return type:

None

async minimize_window()[source]

minimizes the window the current Target belongs to. :rtype: None

Warning

Minimizing isn’t recommended as it can throttle some functionalities in chrome.

async print_page()[source]

Prints the page (current target => tab) to PDF

Return type:

str

property switch_to: SwitchTo

SwitchTo handle

async back()[source]

Goes one step backward in the browser history on the current target (has to be a tab).

Return type:

None

async forward()[source]

Goes one step forward in the browser history on the current target (has to be a tab).

Return type:

None

async refresh()[source]

Refreshes the current tab (target).

Return type:

None

async get_cookies()[source]

list of cookies for the current tab

Return type:

List[dict]

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

Parameters:

name – name of the cookie

Return type:

Optional[Dict]

Deletes a single cookie with the given name in the current tab.

Parameters:
  • name (str) – name of the cookie to delete

  • url (Optional[str]) – url of the cookie

  • domain (Optional[str]) – domain of the cookie

  • path (Optional[str]) – path of the cookie

Return type:

None

async delete_all_cookies()[source]

Delete all cookies in the current (incognito-) context.

Return type:

None

Adds a cookie in the current (incognito-) context

Parameters:

cookie_dict (dict) – see Network.CookieParam

Return type:

None

async static sleep(time_to_wait)[source]

Note

use this one instead of time.sleep in the sync version.

Parameters:

time_to_wait – time in seconds to sleep

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[float]) – how long to wait for the element to exist

Return type:

WebElement

async find_elements(by, value, timeout=3)[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

  • timeout (float) – how long to wait for not being in a page reload loop in seconds

Return type:

List[WebElement]

async search_elements(query)[source]

find elements similarly to how “CTRL+F” in the DevTools Console works

Parameters:

query (str) – Plain text to find elements with

Return type:

List[WebElement]

async get_screenshot_as_file(filename)[source]

Saves a screenshot of the current tab to a PNG image file. :type filename: str :param filename: The path you wish to save your screenshot to. should end with a .png extension.

driver.get_screenshot_as_file('screenshots/test.png')
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 tab 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 set_window_size(width, height)[source]

Sets the width and height of the window, the current tab is within (unless windowHandle specified)

Parameters:
  • width (int) – the width in pixels to set the window to

  • height (int) – the height in pixels to set the window to

Return type:

None

async get_window_size()[source]

Gets the width and height of the current window.

returns something like: .. code-block: json :rtype: dict

{“width”:1280, “height”:720}

async set_window_position(x, y)[source]

Sets the x,y position of the window, the current tab is in.

Parameters:
  • x (int) – the x-coordinate in pixels to set the window position

  • y (int) – the y-coordinate in pixels to set the window position

Return type:

dict

async get_window_position()[source]

Gets the x,y position of the window, the current tab is in.

returns something like: .. code-block: json :rtype: dict

{“x”:0, “y”:0}

async get_window_rect()[source]

Gets the x, y, with and height coordinates of the window, the current tab is in.

returns something like: .. code-block: json :rtype: dict

{“x”:0, “y”:0, “width”:1280, “height”:720, “windowState”:”normal” }

Note

windowState can be one of “normal”, “minimized”, “maximized”, “fullscreen”

async set_window_rect(x=None, y=None, width=None, height=None)[source]

Sets the x, y, width and height coordinates of the window the current target is in.

Parameters:
  • x – the x-coordinate in pixels to set the window position

  • y – the y-coordinate in pixels to set the window position

  • width – the width in pixels to set the window to

  • height – the height in pixels to set the window to

Return type:

dict

Note

either x and y or with and height have to be specified

async get_network_conditions()[source]

Gets Chromium network emulation settings.

returns a dict like:

{"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.

Parameters:
  • offline (bool) –

  • latency (int) – additional latency in ms

  • download_throughput (int) – maximum throughput, 500 * 1024 for example

  • upload_throughput (int) – maximum throughput, 500 * 1024 for example

  • connection_type (Literal['none', 'cellular2g', 'cellular3g', 'cellular4g', 'bluetooth', 'ethernet', 'wifi', 'wimax', 'other']) – the connection type

Return type:

None

Note

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

async delete_network_conditions()[source]

Resets Chromium network emulation settings.

Return type:

None

async set_permissions(name, value, origin=None)[source]

Sets Applicable Permission

Parameters:
  • name (str) – The item to set the permission on.

  • value (Literal['granted', 'denied', 'prompt']) – The value to set on the item

  • origin (Optional[str]) – the origin the permission for. Applies to any origin if not set

Return type:

None

target.set_permissions('clipboard-read', 'denied')
async set_proxy(proxy_config)[source]

set a proxy dynamically

Example parameters:

proxy_config = {
    "mode": "fixed_servers",
    "rules": {
        "proxyForHttp": {
            "scheme": scheme,
            "host": host,
            "port": port
        },
        "proxyForHttps": {
            "scheme": scheme,
            "host": host,
            "port": port
        },
        "proxyForFtp": {
            "scheme": scheme,
            "host": host,
            "port": port
        },
        "fallbackProxy": {
            "scheme": scheme,
            "host": host,
            "port": port
        },
        "bypassList": ["<local>"]
    }
}
Parameters:

proxy_config – see developer.chrome.com/docs/extensions/reference/proxy for reference

for authentification, see webdriver.Chrome.set_auth

async set_single_proxy(proxy, bypass_list=None)[source]

Set a single proxy dynamically to be applied in all contexts.

"http://user1:passwrd1@example.proxy.com:5001/"

Warning

  • Only supported when Chrome has been started with driverless or the extension at selenium_driverless/files/mv3_extension has been loaded into the browser.

  • Socks5 doesn’t support authentication due to crbug#1309413.

async clear_proxy()[source]

Clear the applied proxy (=> use no proxy at all) in all contexts.

async set_auth(username, password, host_with_port)[source]

Set authentication dynamically to be applied in all contexts.

driver.set_auth("user1","passwrd1", "example.com:5001")

Warning

  • Only supported when Chrome has been started with driverless or the extension at selenium_driverless/files/mv3_extension has been loaded into the browser.

  • Socks5 doesn’t support authentication due to crbug#1309413.

Parameters:
  • username (str) –

  • password (str) –

  • host_with_port – in format “example.com:5001”

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

wait for an event on the current target see Target.wait_for_cdp for reference

Return type:

dict

async add_cdp_listener(event, callback)[source]

add a listener for a CDP event on the current target see Target.add_cdp_listener for reference

async remove_cdp_listener(event, callback)[source]

remove a listener for a CDP event on the current target 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 on the current target executes it on Target.execute_cdp_cmd if message:'Not allowed' received see Target.execute_cdp_cmd for reference

Return type:

dict

async fetch(*args, **kwargs)[source]

executes a JS fetch request within the current target see Target.fetch for reference

Return type:

dict

async xhr(*args, **kwargs)[source]

executes a JS XMLHttpRequest request within the current target see Target.fetch for reference

Return type:

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.

Parameters:

sink_name (str) – 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.

Parameters:

sink_name (str) – 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.

Args:
  • sink_name: Name of the sink to stop the Cast session.

Return type:

dict

class selenium_driverless.scripts.switch_to.SwitchTo(context, context_id=None, loop=None)[source]

the SwitchTo class

Warning

except for switching to targets, do not use this class

property alert: Alert

Switches focus to an alert on the page.

Usage:
alert = target.switch_to.alert
async get_alert(timeout=5)[source]

Switches focus to an alert on the page.

Usage:
alert = target.switch_to.alert
Return type:

Alert

async default_content(activate=False)[source]

Switch focus to the default frame.

Usage:
target.switch_to.default_content()
Return type:

Target

async frame(frame_reference, focus=True)[source]

Switches to the specified frame

Parameters:
  • frame_reference (Union[str, int, WebElement]) – the reference by ID, name, index, or WebElement

  • focus (bool) – whether to emulate focus on the frame

  • focus – whether to emulate focus on the iframe

Return type:

None

async target(target_id, activate=False, focus=True)[source]

switches to a target

Parameters:
  • target_id (Union[str, TargetInfo, Target]) – the target to switch to

  • activate (bool) – whether to bring the target to the front

  • focus (bool) – whether to emulate focus on the target

Return type:

Target

async window(window_id, activate=False, focus=True)[source]

switches to a window

alias to SwitchTo.target <selenium_driverless.scripts.switch_to.SwitchTo.target()

Return type:

Target

async new_window(type_hint='tab', url='', activate=False, focus=True, background=True)[source]

creates a new tab or window

Parameters:
  • type_hint (Literal['tab', 'window']) – what kind of target to create

  • url – url to start the target at

  • activate (bool) – whether to bring the target to the front

  • focus (bool) – whether to emulate focus on the target

  • background (bool) – whether to start the target in the background

Return type:

Target