Context

class selenium_driverless.types.context.Context(base_target, driver, context_id=None, loop=None, is_incognito=False, max_ws_size=1048576)[source]

Allows you to drive the browser without chromedriver.

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

set the download behaviour

Parameters:
  • behavior (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 downloads_dir

the current downloads directory

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:

dict

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

property title: str

Returns the title of the current target

property current_pointer: Pointer

the Pointer for the current 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=None, max_depth=None, timeout=2, target_id=None, execution_context_id=None, unique_context=False)[source]

example: script= “function(…arguments){obj.click()}” “const obj” will be the Object according to obj_id this is by default globalThis (=> window)

async execute_script(script, *args, max_depth=2, serialization=None, timeout=None, target_id=None, execution_context_id=None, unique_context=False)[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=2, target_id=None, execution_context_id=None, unique_context=False)[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]

this refers to globalThis (=> window)

see Target.execute_raw_script for argument descriptions

async eval_async(script, *args, max_depth=2, serialization=None, timeout=2, target_id=None, execution_context_id=None, unique_context=False)[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 docs_source of the current page.

Usage:
target.page_source
async close(timeout=2, target_id=None)[source]

Closes the current window.

Usage:
target.close()
Return type:

None

async quit(timeout=30, start_monotonic=None)[source]

Quits the target and closes every associated window.

Usage:
target.quit()
Return type:

None

property current_window_handle: str

Returns the current target_id

property window_handles: List[TargetInfo]

Returns the handles of all windows within the current session.

Usage:
target.window_handles
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

async maximize_window()[source]

Maximizes the current window that webdriver is using.

Return type:

None

async fullscreen_window()[source]

Invokes the window manager-specific ‘full screen’ operation.

Return type:

None

async minimize_window()[source]

Invokes the window manager-specific ‘minimize’ operation.

Return type:

None

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.

Return type:

str

property switch_to: SwitchTo
Returns:
  • SwitchTo: an object containing all options to switch focus into

Usage:
element = target.switch_to.active_element
alert = target.switch_to.alert
target.switch_to.default_content()
target.switch_to.frame('frame_name')
target.switch_to.frame(1)
target.switch_to.frame(target.find_elements(By.TAG_NAME, "iframe")[0])
target.switch_to.parent_frame()
target.switch_to.window('main')
async back(target_id=None)[source]

Goes one step backward in the browser history.

Usage:
target.back()
Return type:

None

async forward(target_id=None)[source]

Goes one step forward in the browser history.

Usage:
target.forward()
Return type:

None

async refresh(target_id=None)[source]

Refreshes the current page.

Usage:
target.refresh()
Return type:

None

async get_cookies(target_id=None)[source]

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

Return type:

List[dict]

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

Usage:
target.get_cookie('my_cookie')
Return type:

Optional[Dict]

Deletes a single cookie with the given name.

Return type:

None

async delete_all_cookies(target_id=None)[source]

Delete all cookies in the scope of the session.

Usage:
target.delete_all_cookies()
Return type:

None

Adds a cookie to your current session.

Parameters:

cookie_dict (dict) – A dictionary object, with required keys - “name” and “value”; optional keys - “path”, “domain”, “secure”, “httpOnly”, “expiry”, “sameSite”

Usage:
target.add_cookie({'name' : 'foo', 'value' : 'bar'})
target.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
target.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure' : True})
target.add_cookie({'name' : 'foo', 'value' : 'bar', 'sameSite' : 'Strict'})
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 search_elements(query, target_id=None)[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 you wish to save your screenshot to. 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(target_id=None)[source]

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

Usage:
target.get_screenshot_as_png()
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, windowHandle='current')[source]

Sets the width and height of the current window. (window.resizeTo)

Args:
  • width: the width in pixels to set the window to

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

Usage:
target.set_window_size(800,600)
Return type:

None

async get_window_size()[source]

Gets the width and height of the current window.

Return type:

dict

async set_window_position(x, y, windowHandle='current')[source]

Sets the x,y position of the current window. (window.moveTo)

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

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

Usage:
target.set_window_position(0,0)
Return type:

dict

async get_window_position(windowHandle='current')[source]

Gets the x,y position of the current window.

Usage:
target.get_window_position()
Return type:

dict

async get_window_rect()[source]

Gets the x, y coordinates of the window as well as height and width of the current window.

Usage:
target.get_window_rect()
Return type:

dict

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

Sets the x, y coordinates of the window as well as height and width of the current window. This method is only supported for W3C compatible browsers; other browsers should use set_window_position and set_window_size.

Usage:
target.set_window_rect(x=10, y=10)
target.set_window_rect(width=100, height=200)
target.set_window_rect(x=10, y=10, width=100, height=200)
Return type:

dict

async get_network_conditions(target_id=None)[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, target_id=None)[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(target_id=None)[source]

Resets Chromium network emulation settings.

Return type:

None

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

Sets Applicable Permission.

Args:
  • name: The item to set the permission on.

  • value: The value to set on the item

Usage:
target.set_permissions('clipboard-read', 'denied')
Return type:

None

async wait_for_cdp(event, timeout=None, target_id=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, target_id=None)[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, target_id=None)[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, target_id=None)[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, target_id=None)[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(target_id=None)[source]
Returns:

A list of sinks available for Cast.

Return type:

list

async get_issue_message(target_id=None)[source]
Returns:

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

async set_sink_to_use(sink_name, target_id=None)[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, target_id=None)[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, target_id=None)[source]

Starts a tab mirroring session on a specific receiver target.

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

Return type:

dict

async stop_casting(sink_name, target_id=None)[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