selenium.webdriver.safari.webdriver#
Classes
|
Controls the SafariDriver and allows you to drive the browser. |
- class WebDriver(*args, **kwargs)[source]#
Bases:
LocalWebDriverControls the SafariDriver and allows you to drive the browser.
Create a new Safari driver instance and launch or find a running safaridriver service.
- Parameters:
- add_cookie(cookie_dict)[source]#
Adds a cookie to your current session.
- Parameters:
cookie_dict – A dictionary object, with required keys - “name” and “value”; Optional keys - “path”, “domain”, “secure”, “httpOnly”, “expiry”, “sameSite”.
- Return type:
None
Examples
driver.add_cookie({“name”: “foo”, “value”: “bar”}) driver.add_cookie({“name”: “foo”, “value”: “bar”, “path”: “/”}) driver.add_cookie({“name”: “foo”, “value”: “bar”, “path”: “/”, “secure”: True}) driver.add_cookie({“name”: “foo”, “value”: “bar”, “sameSite”: “Strict”})
- add_credential(credential)[source]#
Injects a credential into the authenticator.
Example
``` from selenium.webdriver.common.credential import Credential
credential = Credential(id=”user@example.com”, password=”aPassword”) driver.add_credential(credential) ```
- Parameters:
credential (Credential)
- Return type:
None
- add_virtual_authenticator(options)[source]#
Adds a virtual authenticator with the given options.
Example
``` from selenium.webdriver.common.virtual_authenticator import VirtualAuthenticatorOptions
options = VirtualAuthenticatorOptions(protocol=”u2f”, transport=”usb”, device_id=”myDevice123”) driver.add_virtual_authenticator(options) ```
- Parameters:
options (VirtualAuthenticatorOptions)
- Return type:
None
- property browser: Browser#
Returns a browser module object for BiDi browser commands.
- Returns:
An object containing access to BiDi browser commands.
Examples
user_context = driver.browser.create_user_context() user_contexts = driver.browser.get_user_contexts() client_windows = driver.browser.get_client_windows() driver.browser.remove_user_context(user_context)
- property browsing_context: BrowsingContext#
Returns a browsing context module object for BiDi browsing context commands.
- Returns:
An object containing access to BiDi browsing context commands.
Examples
context_id = driver.browsing_context.create(type=”tab”) driver.browsing_context.navigate(context=context_id, url=”https://www.selenium.dev”) driver.browsing_context.capture_screenshot(context=context_id) driver.browsing_context.close(context_id)
- property capabilities: dict#
Returns the drivers current capabilities being used.
- create_web_element(element_id)[source]#
Creates a web element with the specified element_id.
- Parameters:
element_id (str)
- Return type:
- property current_url: str#
Gets the URL of the current page.
- property current_window_handle: str#
Returns the handle of the current window.
- delete_cookie(name)[source]#
Delete a single cookie with the given name (case-sensitive).
- Raises:
ValueError if the name is empty or whitespace. –
- Return type:
None
Example
driver.delete_cookie(“my_cookie”)
- delete_downloadable_files(*args, **kwargs)#
Only implemented in RemoteWebDriver.
- download_file(*args, **kwargs)#
Only implemented in RemoteWebDriver.
- property emulation: Emulation#
Get an emulation module object for BiDi emulation commands.
- Returns:
An object containing access to BiDi emulation commands.
Examples
``` from selenium.webdriver.common.bidi.emulation import GeolocationCoordinates
coordinates = GeolocationCoordinates(37.7749, -122.4194) driver.emulation.set_geolocation_override(coordinates=coordinates, contexts=[context_id]) ```
- execute(driver_command, params=None)[source]#
Sends a command to be executed by a command.CommandExecutor.
- Parameters:
driver_command (str | Generator[dict[str, Any], Any, Any]) – The name of the command to execute as a string. Can also be a BiDi protocol command generator.
params (dict[str, Any] | None) – A dictionary of named parameters to send with the command. Ignored when
driver_commandis a BiDi generator.
- Returns:
The command’s JSON response loaded into a dictionary object.
- Return type:
Any
- execute_async_script(script, *args)[source]#
Asynchronously Executes JavaScript in the current window/frame.
- Parameters:
script (str) – The javascript to execute.
*args – Any applicable arguments for your JavaScript.
- Return type:
Any
Example
``` script = “var callback = arguments[arguments.length - 1]; “
“window.setTimeout(function(){ callback(‘timeout’) }, 3000);”
- execute_cdp_cmd(cmd, cmd_args)[source]#
Execute Chrome Devtools Protocol command and get returned result.
- The command and command args should follow chrome devtools protocol domains/commands:
- Parameters:
cmd (str) – Command name.
cmd_args (dict) – Command args. Empty dict {} if there is no command args.
- Returns:
A dict, empty dict {} if there is no result to return. To getResponseBody: {‘base64Encoded’: False, ‘body’: ‘response body string’}
Example
driver.execute_cdp_cmd(“Network.getResponseBody”, {“requestId”: requestId})
- execute_script(script, *args)[source]#
Synchronously Executes JavaScript in the current window/frame.
- Parameters:
script (str) – The javascript to execute.
*args – Any applicable arguments for your JavaScript.
- Return type:
Any
Example
` id = "username" value = "test_user" driver.execute_script("document.getElementById(arguments[0]).value = arguments[1];", id, value) `
- property fedcm: FedCM#
Get the Federated Credential Management (FedCM) dialog commands.
- Returns:
An object providing access to all Federated Credential Management (FedCM) dialog commands.
Examples
driver.fedcm.title driver.fedcm.subtitle driver.fedcm.dialog_type driver.fedcm.account_list driver.fedcm.select_account(0) driver.fedcm.accept() driver.fedcm.dismiss() driver.fedcm.enable_delay() driver.fedcm.disable_delay() driver.fedcm.reset_cooldown()
- fedcm_dialog(timeout=5, poll_frequency=0.5, ignored_exceptions=None)[source]#
Waits for and returns the FedCM dialog.
- Parameters:
timeout – How long to wait for the dialog.
poll_frequency – How frequently to poll.
ignored_exceptions – Exceptions to ignore while waiting.
- Returns:
The FedCM dialog object if found.
- Raises:
TimeoutException – If dialog doesn’t appear.
WebDriverException – If FedCM not supported.
- property file_detector: FileDetector#
- file_detector_context(file_detector_class, *args, **kwargs)[source]#
Override the current file detector temporarily within a limited context.
Ensures the original file detector is set after exiting the context.
- Parameters:
file_detector_class – Class of the desired file detector. If the class is different from the current file_detector, then the class is instantiated with args and kwargs and used as a file detector during the duration of the context manager.
*args – Optional arguments that get passed to the file detector class during instantiation.
**kwargs – Keyword arguments, passed the same way as args.
Example
``` with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys(“/etc/hosts”)
- find_element(by='id', value=None)[source]#
Find an element given a By strategy and locator.
- Parameters:
by (str | By | RelativeBy) – The locating strategy to use. Default is By.ID. Supported values include: By.ID, By.NAME, By.XPATH, By.CSS_SELECTOR, By.CLASS_NAME, By.TAG_NAME, By.LINK_TEXT, By.PARTIAL_LINK_TEXT, or RelativeBy.
value (str | None) – The locator value to use with the specified by strategy.
- Returns:
The first matching WebElement found on the page.
- Return type:
Example
element = driver.find_element(By.ID, ‘foo’)
- find_elements(by='id', value=None)[source]#
Find elements given a By strategy and locator.
- Parameters:
by (str | By | RelativeBy) – The locating strategy to use. Default is By.ID. Supported values include: By.ID, By.NAME, By.XPATH, By.CSS_SELECTOR, By.CLASS_NAME, By.TAG_NAME, By.LINK_TEXT, By.PARTIAL_LINK_TEXT, or RelativeBy.
value (str | None) – The locator value to use with the specified by strategy.
- Returns:
List of WebElements matching locator strategy found on the page.
- Return type:
list[WebElement]
Example
element = driver.find_elements(By.ID, ‘foo’)
- fire_session_event(event_type, payload=None)[source]#
Fire a custom session event to the remote server event bus.
This allows test code to trigger server-side utilities that subscribe to the event bus.
- Parameters:
event_type (str) – The type of event (e.g., “test:failed”, “log:collect”, “marker:add”).
payload (dict | None) – Optional data to include with the event.
- Returns:
A dictionary containing the response data including success status, event type, and timestamp.
- Raises:
WebDriverException – If the event cannot be fired.
- Return type:
dict
Examples
Simple event:
driver.fire_session_event("test:started")
Event with payload:
driver.fire_session_event("test:failed", {"testName": "LoginTest", "error": "Element not found"})
- fullscreen_window()[source]#
Invokes the window manager-specific ‘full screen’ operation.
- Return type:
None
- get(url)[source]#
Navigate the browser to the specified URL.
The method does not return until the page is fully loaded (i.e. the onload event has fired) in the current window or tab.
- Parameters:
url (str) – The URL to be opened by the browser. Must include the protocol (e.g., http://, https://).
- Return type:
None
Example
driver.get(“https://example.com”)
- get_cookie(name)[source]#
Get a single cookie by name (case-sensitive,).
- Returns:
A cookie dictionary or None if not found.
- Raises:
ValueError if the name is empty or whitespace. –
- Return type:
dict | None
Example
cookie = driver.get_cookie(“my_cookie”)
- get_cookies()[source]#
Get all cookies visible to the current WebDriver instance.
- Returns:
A list of dictionaries, corresponding to cookies visible in the current session.
- Return type:
list[dict]
- get_credentials()[source]#
Returns the list of credentials owned by the authenticator.
- Return type:
list[Credential]
- get_downloadable_files(*args, **kwargs)#
Only implemented in RemoteWebDriver.
- get_pinned_scripts()[source]#
Return a list of all pinned scripts.
Deprecated since version Use:
driver.script.pin()to manage preload scripts via the WebDriver BiDi protocol.Example
pinned_scripts = driver.get_pinned_scripts()
- Return type:
list[str]
- get_screenshot_as_base64()[source]#
Get a base64-encoded screenshot of the current window.
This encoding is useful for embedding screenshots in HTML.
Example
driver.get_screenshot_as_base64()
- Return type:
str
- get_screenshot_as_file(filename)[source]#
Save a screenshot of the current window to a PNG image file.
- Returns:
False if there is any IOError, else returns True. Use full paths in your filename.
- Parameters:
filename – The full path you wish to save your screenshot to. This should end with a .png extension.
- Return type:
bool
Example
driver.get_screenshot_as_file(“./screenshots/foo.png”)
- get_screenshot_as_png()[source]#
Gets the screenshot of the current window as a binary data.
Example
driver.get_screenshot_as_png()
- Return type:
bytes
- get_window_position(windowHandle='current')[source]#
Gets the x,y position of the current window.
Example
driver.get_window_position()
- Return type:
dict
- get_window_rect()[source]#
Get the window’s position and size.
- Returns:
x, y coordinates and height and width of the current window.
- Return type:
dict
Example
driver.get_window_rect()
- get_window_size(windowHandle='current')[source]#
Gets the width and height of the current window.
Example
driver.get_window_size()
- Parameters:
windowHandle (str)
- Return type:
dict
- implicitly_wait(time_to_wait)[source]#
Set a sticky implicit timeout for element location and command completion.
This method sets a timeout that applies to all element location strategies for the duration of the session. It only needs to be called once per session. To set the timeout for asynchronous script execution, see set_script_timeout.
- Parameters:
time_to_wait (float) – Amount of time to wait (in seconds).
- Return type:
None
Example
driver.implicitly_wait(30)
- property input: Input#
Get an input module object for BiDi input commands.
- Returns:
An object containing access to BiDi input commands.
Examples
``` from selenium.webdriver.common.bidi.input import KeySourceActions, KeyDownAction, KeyUpAction
actions = KeySourceActions(id=”keyboard”, actions=[KeyDownAction(value=”a”), KeyUpAction(value=”a”)]) driver.input.perform_actions(driver.current_window_handle, [actions]) driver.input.release_actions(driver.current_window_handle) ```
- minimize_window()[source]#
Invokes the window manager-specific ‘minimize’ operation.
- Return type:
None
- property name: str#
Returns the name of the underlying browser for this instance.
- property network: Network#
- property orientation: dict#
Gets the current orientation of the device.
Example
orientation = driver.orientation
- property page_source: str#
Gets the source of the current page.
- property permissions: Permissions#
Get a permissions module object for BiDi permissions commands.
- Returns:
An object containing access to BiDi permissions commands.
Examples
``` from selenium.webdriver.common.bidi.permissions import PermissionDescriptor, PermissionState
descriptor = PermissionDescriptor(“geolocation”) driver.permissions.set_permission(descriptor, PermissionState.GRANTED, “https://example.com”) ```
- pin_script(script, script_key=None)[source]#
Store a JavaScript script by a unique hashable ID for later execution.
Deprecated since version Use:
driver.script.pin()instead, which uses the WebDriver BiDi protocol.Example
script = “return document.getElementById(‘foo’).value”
- Parameters:
script (str)
- Return type:
- print_page(print_options=None)[source]#
Takes PDF of the current page.
The driver makes a best effort to return a PDF based on the provided parameters.
- Parameters:
print_options (PrintOptions | None)
- Return type:
str
- remove_credential(credential_id)[source]#
Removes a credential from the authenticator.
Example
credential_id = “user@example.com” driver.remove_credential(credential_id)
- Parameters:
credential_id (str | bytearray)
- Return type:
None
- remove_virtual_authenticator()[source]#
Removes a previously added virtual authenticator.
The authenticator is no longer valid after removal, so no methods may be called.
- Return type:
None
- property request: APIRequestContext#
Returns an APIRequestContext for making HTTP requests with browser cookie sync.
- Returns:
An APIRequestContext instance bound to this driver.
Examples
` response = driver.request.get("https://api.example.com/data") assert response.ok data = response.json() `
- save_screenshot(filename)[source]#
Save a screenshot of the current window to a PNG image file.
- Returns:
False if there is any IOError, else returns True. Use full paths in your filename.
- Parameters:
filename – The full path you wish to save your screenshot to. This should end with a .png extension.
- Return type:
bool
Example
driver.save_screenshot(“./screenshots/foo.png”)
- property script: Script#
- set_page_load_timeout(time_to_wait)[source]#
Set the timeout for page load completion.
This specifies how long to wait for a page load to complete before throwing an error.
- Parameters:
time_to_wait (float) – The amount of time to wait (in seconds).
- Return type:
None
Example
driver.set_page_load_timeout(30)
- set_script_timeout(time_to_wait)[source]#
Set the timeout for asynchronous script execution.
This timeout specifies how long a script can run during an execute_async_script call before throwing an error.
- Parameters:
time_to_wait (float) – The amount of time to wait (in seconds).
- Return type:
None
Example
driver.set_script_timeout(30)
- set_user_verified(verified)[source]#
Set whether the authenticator will simulate success or failure on user verification.
- Parameters:
verified (bool) – True if the authenticator will pass user verification, False otherwise.
- Return type:
None
Example
driver.set_user_verified(True)
- set_window_position(x, y, windowHandle='current')[source]#
Sets the x,y position of the current window.
- Parameters:
x (float) – The x-coordinate in pixels to set the window position.
y (float) – The y-coordinate in pixels to set the window position.
windowHandle (str) – The handle of the window to reposition. Default is “current”.
- Return type:
dict
Example
driver.set_window_position(0, 0)
- set_window_rect(x=None, y=None, width=None, height=None)[source]#
Set the window’s position and size.
Sets the x, y coordinates and 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.
Example
driver.set_window_rect(x=10, y=10) driver.set_window_rect(width=100, height=200) driver.set_window_rect(x=10, y=10, width=100, height=200)
- Return type:
dict
- set_window_size(width, height, windowHandle='current')[source]#
Sets the width and height of the current window.
- Parameters:
width – The width in pixels to set the window to.
height – The height in pixels to set the window to.
windowHandle (str) – The handle of the window to resize. Default is “current”.
- Return type:
None
Example
driver.set_window_size(800, 600)
- start_client()[source]#
Called before starting a new session.
This method may be overridden to define custom startup behavior.
- Return type:
None
- start_devtools()[source]#
- Return type:
tuple[Any, WebSocketConnection]
- start_session(capabilities)[source]#
Creates a new session with the desired capabilities.
- Parameters:
capabilities (dict) – A capabilities dict to start the session with.
- Return type:
None
- stop_client()[source]#
Called after executing a quit command.
This method may be overridden to define custom shutdown behavior.
- Return type:
None
- property storage: Storage#
Returns a storage module object for BiDi storage commands.
- Returns:
An object containing access to BiDi storage commands.
Examples
` cookie_filter = CookieFilter(name="example") result = driver.storage.get_cookies(filter=cookie_filter) cookie=PartialCookie("name", BytesValue(BytesValue.TYPE_STRING, "value") driver.storage.set_cookie(cookie=cookie, "domain")) cookie_filter=CookieFilter(name="example") driver.storage.delete_cookies(filter=cookie_filter) `
- property supports_fedcm: bool#
Returns whether the browser supports FedCM capabilities.
- property switch_to: SwitchTo#
Return an object containing all options to switch focus into.
- Returns:
An object containing all options to switch focus into.
Examples
element = driver.switch_to.active_element alert = driver.switch_to.alert driver.switch_to.default_content() driver.switch_to.frame(“frame_name”) driver.switch_to.frame(1) driver.switch_to.frame(driver.find_elements(By.TAG_NAME, “iframe”)[0]) driver.switch_to.parent_frame() driver.switch_to.window(“main”)
- property timeouts: Timeouts#
Get all the timeouts that have been set on the current session.
- Returns:
implicit_wait: The time to wait for elements to be found.
page_load: The time to wait for a page to load.
script: The time to wait for scripts to execute.
- Return type:
A named tuple with the following fields
Example
driver.timeouts
- property title: str#
Returns the title of the current page.
Example
` element = driver.find_element(By.ID, "foo") print(element.title()) `
- unpin(script_key)[source]#
Remove a pinned script from storage.
Deprecated since version Use:
driver.script.unpin()instead, which uses the WebDriver BiDi protocol.Example
driver.unpin(script_key)
- Parameters:
script_key (ScriptKey)
- Return type:
None
- property virtual_authenticator_id: str | None#
Returns the id of the virtual authenticator.
- property webextension: WebExtension#
Get a webextension module object for BiDi webextension commands.
- Returns:
An object containing access to BiDi webextension commands.
Examples
extension_path = “/path/to/extension” extension_result = driver.webextension.install(path=extension_path) driver.webextension.uninstall(extension_result)
- property window_handles: list[str]#
Returns the handles of all windows within the current session.