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
- 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 defaultuniversal_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:
Warning
The proxy parameter doesn’t work on Windows due to crbug#1310057.
- Parameters:
proxy_server (
str) – a proxy-server to use for the contextproxy_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: ifNone, this function returns all targets for all contexts.- Return type:
Dict[str,TargetInfo]
- 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,spanningornot_allowedconfiguration. For changing this behaviour, you’ll have to modify themanifest.jsonfile within the compressed extension or directory. See developer.chrome.com/docs/extensions/reference/manifest/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 topath (
Optional[str]) – the path to the default download directory
Warning
setting
behaviour=allowinstead ofallowAndNamecan cause some bugs
- 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:
- 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_documentinstead- Parameters:
iframe (
WebElement) – the iframe to get the Target for- Return type:
- async get_targets_for_iframes(iframes)[source]
returns a list of targets for iframes see
webdriver.Chrome.get_target_for_iframefor 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 withwait_load (
bool) – whether to wait for the webpage to loadtimeout (
float) – the maximum time in seconds for waiting on load
- Return type:
Optional[dict]
returns the same as
Target.wait_downloadif the url initiates a download
- property title: str
async the title of 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='deep', max_depth=None, timeout=2, execution_context_id, unique_context=True)[source]
executes a JavaScript on
GlobalThissuch asfunction(...arguments){return document}
- Parameters:
script (
str) – the script as a stringargs – 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 itserialization (
Literal['deep','json','idOnly']) – can be one ofdeep,json,idOnlymax_depth (
Optional[int]) – The maximum depth objects get serialized.timeout (
float) – the maximum time to wait for the execution to completeexecution_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.
- async execute_script(script, *args, max_depth=2, serialization=None, timeout=2, execution_context_id=None, unique_context=True)[source]
executes JavaScript synchronously on
GlobalThissuch asreturn document
see
Target.execute_raw_scriptfor 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
GlobalThissuch asWarning
using execute_async_script is not recommended as it doesn’t handle exceptions correctly. Use
Chrome.eval_asyncresolve = arguments[arguments.length-1]
see
Target.execute_raw_scriptfor 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
GlobalThissuch asres = await fetch("https://httpbin.org/get"); // mind CORS! json = await res.json() return json
see
Target.execute_raw_scriptfor 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 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.idinstead
- property current_window_id
async the
WindowIdof 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 windowurl – the url which the new window should start on. Defaults to about:blank
activate (
bool) – whether to explicitly activate/focus the window
- Return type:
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:
NoneWarning
Minimizing isn’t recommended as it can throttle some functionalities in chrome.
- 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 get_cookie(name)[source]
Get a single cookie by name. Returns the cookie if found, None if not.
- Parameters:
name – name of the cookie
- Return type:
Optional[Dict]
- async delete_cookie(name, url=None, domain=None, path=None)[source]
Deletes a single cookie with the given name in the current tab.
- Parameters:
name (
str) – name of the cookie to deleteurl (
Optional[str]) – url of the cookiedomain (
Optional[str]) – domain of the cookiepath (
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
- async add_cookie(cookie_dict)[source]
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 atByvalue (
str) – the actual query to find the element bytimeout (
Optional[float]) – how long to wait for the element to exist
- Return type:
- async find_elements(by, value, timeout=3)[source]
find multiple elements in the current target
- Parameters:
by (
str) – one of the locators atByvalue (
str) – the actual query to find the elements bytimeout (
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 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.mhtmlextension.
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
windowHandlespecified)- Parameters:
width (
int) – the width in pixels to set the window toheight (
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 positiony (
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
windowStatecan 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 msdownload_throughput (
int) – maximum throughput, 500 * 1024 for exampleupload_throughput (
int) – maximum throughput, 500 * 1024 for exampleconnection_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 itemorigin (
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_extensionhas been loaded into the browser.Socks5doesn’t support authentication due to crbug#1309413.
- 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_extensionhas been loaded into the browser.Socks5doesn’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_cdpfor 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_listenerfor reference
- async remove_cdp_listener(event, callback)[source]
remove a listener for a CDP event on the current target see
Target.remove_cdp_listenerfor reference
- async get_cdp_event_iter(event)[source]
iterate over CDP events on the current target see
Target.get_cdp_event_iterfor 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_cmdifmessage:'Not allowed'received seeTarget.execute_cdp_cmdfor reference- Return type:
dict
- async fetch(*args, **kwargs)[source]
executes a JS
fetchrequest within the current target seeTarget.fetchfor reference- Return type:
dict
- async xhr(*args, **kwargs)[source]
executes a JS
XMLHttpRequestrequest within the current target seeTarget.fetchfor reference- Return type:
dict
- 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
- 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:
- 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 WebElementfocus (
bool) – whether to emulate focus on the framefocus – 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 toactivate (
bool) – whether to bring the target to the frontfocus (
bool) – whether to emulate focus on the target
- Return type:
- 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:
- 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 createurl – url to start the target at
activate (
bool) – whether to bring the target to the frontfocus (
bool) – whether to emulate focus on the targetbackground (
bool) – whether to start the target in the background
- Return type: