selenium.webdriver.remote.webdriver¶
The WebDriver implementation.
Functions
|
|
|
|
Classes
Abstract Base Class for all Webdriver subtypes. |
|
|
Control a browser by sending commands to a remote WebDriver server. |
- selenium.webdriver.remote.webdriver.get_remote_connection(capabilities: dict, command_executor: str | RemoteConnection, keep_alive: bool, ignore_local_proxy: bool, client_config: ClientConfig | None = None) RemoteConnection[source]¶
- selenium.webdriver.remote.webdriver.create_matches(options: list[BaseOptions]) dict[source]¶
- class selenium.webdriver.remote.webdriver.BaseWebDriver[source]¶
Abstract Base Class for all Webdriver subtypes.
ABC’s allow custom implementations of Webdriver to be registered so that isinstance type checks will succeed.
- class selenium.webdriver.remote.webdriver.WebDriver(command_executor: str | RemoteConnection = 'http://127.0.0.1:4444', keep_alive: bool = True, file_detector: FileDetector | None = None, options: BaseOptions | list[BaseOptions] | None = None, locator_converter: LocatorConverter | None = None, web_element_cls: type[WebElement] | None = None, client_config: ClientConfig | None = None)[source]¶
Control a browser by sending commands to a remote WebDriver server.
This class expects the remote server to be running the WebDriver wire protocol as defined at https://www.selenium.dev/documentation/legacy/json_wire_protocol/.
Attributes:¶
session_id - String ID of the browser session started and controlled by this WebDriver. capabilities - Dictionary of effective capabilities of this browser session as returned
by the remote server. See https://www.selenium.dev/documentation/legacy/desired_capabilities/
command_executor : str or remote_connection.RemoteConnection object used to execute commands. error_handler - errorhandler.ErrorHandler object used to handle errors.
Create a new driver instance that issues commands using the WebDriver protocol.
- Args:
- command_executor: Either a string representing the URL of the remote
server or a custom remote_connection.RemoteConnection object. Defaults to ‘http://127.0.0.1:4444/wd/hub’.
- keep_alive: (Deprecated) Whether to configure
remote_connection.RemoteConnection to use HTTP keep-alive. Defaults to True.
- file_detector: Pass a custom file detector object during
instantiation. If None, the default LocalFileDetector() will be used.
options: Instance of a driver options.Options class. locator_converter: Custom locator converter to use. Defaults to None. web_element_cls: Custom class to use for web elements. Defaults to
WebElement.
client_config: Custom client configuration to use. Defaults to None.
- 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.
- Args:
- 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”)
- property name: str¶
Returns the name of the underlying browser for this instance.
- start_client() None[source]¶
Called before starting a new session.
This method may be overridden to define custom startup behavior.
- stop_client() None[source]¶
Called after executing a quit command.
This method may be overridden to define custom shutdown behavior.
- start_session(capabilities: dict) None[source]¶
Creates a new session with the desired capabilities.
- Args:
capabilities: A capabilities dict to start the session with.
- create_web_element(element_id: str) WebElement[source]¶
Creates a web element with the specified element_id.
- execute_cdp_cmd(cmd: str, cmd_args: dict)[source]¶
Execute Chrome Devtools Protocol command and get returned result.
- The command and command args should follow chrome devtools protocol domains/commands:
- Args:
cmd: Command name. cmd_args: 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(driver_command: str, params: dict[str, Any] | None = None) dict[str, Any][source]¶
Sends a command to be executed by a command.CommandExecutor.
- Args:
driver_command: The name of the command to execute as a string. params: A dictionary of named parameters to send with the command.
- Returns:
The command’s JSON response loaded into a dictionary object.
- get(url: str) None[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.
- property title: str¶
Returns the title of the current page.
- Example:
` element = driver.find_element(By.ID, "foo") print(element.title()) `
- pin_script(script: str, script_key=None) ScriptKey[source]¶
Store a JavaScript script by a unique hashable ID for later execution.
- Example:
script = “return document.getElementById(‘foo’).value”
- unpin(script_key: ScriptKey) None[source]¶
Remove a pinned script from storage.
- Example:
driver.unpin(script_key)
- get_pinned_scripts() list[str][source]¶
Return a list of all pinned scripts.
- Example:
pinned_scripts = driver.get_pinned_scripts()
- execute_script(script: str, *args)[source]¶
Synchronously Executes JavaScript in the current window/frame.
- Args:
script: The javascript to execute. *args: Any applicable arguments for your JavaScript.
- Example:
` id = "username" value = "test_user" driver.execute_script("document.getElementById(arguments[0]).value = arguments[1];", id, value) `
- execute_async_script(script: str, *args) dict[source]¶
Asynchronously Executes JavaScript in the current window/frame.
- property current_url: str¶
Gets the URL of the current page.
- property page_source: str¶
Gets the source of the current page.
- property current_window_handle: str¶
Returns the handle of the current window.
- property window_handles: list[str]¶
Returns the handles of all windows within the current session.
- print_page(print_options: PrintOptions | None = None) str[source]¶
Takes PDF of the current page.
The driver makes a best effort to return a PDF based on the provided parameters.
- 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”)
- get_cookies() list[dict][source]¶
Get all cookies visible to the current WebDriver instance.
- Returns:
A list of dictionaries, corresponding to cookies visible in the current session.
- get_cookie(name) dict | None[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.
- Example:
cookie = driver.get_cookie(“my_cookie”)
- delete_cookie(name) None[source]¶
Delete a single cookie with the given name (case-sensitive).
- Raises:
ValueError if the name is empty or whitespace.
- Example:
driver.delete_cookie(“my_cookie”)
- add_cookie(cookie_dict) None[source]¶
Adds a cookie to your current session.
- Args:
- cookie_dict: A dictionary object, with required keys - “name” and
“value”; Optional keys - “path”, “domain”, “secure”, “httpOnly”, “expiry”, “sameSite”.
- 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”})
- implicitly_wait(time_to_wait: float) None[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.
- Args:
time_to_wait: Amount of time to wait (in seconds).
- Example:
driver.implicitly_wait(30)
- set_script_timeout(time_to_wait: float) None[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.
- Args:
time_to_wait: The amount of time to wait (in seconds).
- Example:
driver.set_script_timeout(30)
- set_page_load_timeout(time_to_wait: float) None[source]¶
Set the timeout for page load completion.
This specifies how long to wait for a page load to complete before throwing an error.
- Args:
time_to_wait: The amount of time to wait (in seconds).
- Example:
driver.set_page_load_timeout(30)
- property timeouts: Timeouts¶
Get all the timeouts that have been set on the current session.
- Returns:
- A named tuple with the following fields:
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.
- Example:
driver.timeouts
- find_element(by='id', value: str | None = None) WebElement[source]¶
Find an element given a By strategy and locator.
- Args:
- by: 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: The locator value to use with the specified by strategy.
- Returns:
The first matching WebElement found on the page.
- Example:
element = driver.find_element(By.ID, ‘foo’)
- find_elements(by='id', value: str | None = None) list[WebElement][source]¶
Find elements given a By strategy and locator.
- Args:
- by: 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: The locator value to use with the specified by strategy.
- Returns:
List of WebElements matching locator strategy found on the page.
- Example:
element = driver.find_elements(By.ID, ‘foo’)
- property capabilities: dict¶
Returns the drivers current capabilities being used.
- get_screenshot_as_file(filename) bool[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.
- Args:
- filename: The full path you wish to save your screenshot to. This
should end with a .png extension.
- Example:
driver.get_screenshot_as_file(“./screenshots/foo.png”)
- save_screenshot(filename) bool[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.
- Args:
- filename: The full path you wish to save your screenshot to. This
should end with a .png extension.
- Example:
driver.save_screenshot(“./screenshots/foo.png”)
- get_screenshot_as_png() bytes[source]¶
Gets the screenshot of the current window as a binary data.
- Example:
driver.get_screenshot_as_png()
- get_screenshot_as_base64() str[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()
- set_window_size(width, height, windowHandle: str = 'current') None[source]¶
Sets the width and height of the current window.
- Args:
width: The width in pixels to set the window to. height: The height in pixels to set the window to. windowHandle: The handle of the window to resize. Default is “current”.
- Example:
driver.set_window_size(800, 600)
- get_window_size(windowHandle: str = 'current') dict[source]¶
Gets the width and height of the current window.
- Example:
driver.get_window_size()
- set_window_position(x: float, y: float, windowHandle: str = 'current') dict[source]¶
Sets the x,y position of the current window.
- Args:
x: The x-coordinate in pixels to set the window position. y: The y-coordinate in pixels to set the window position. windowHandle: The handle of the window to reposition. Default is “current”.
- Example:
driver.set_window_position(0, 0)
- get_window_position(windowHandle='current') dict[source]¶
Gets the x,y position of the current window.
- Example:
driver.get_window_position()
- get_window_rect() dict[source]¶
Get the window’s position and size.
- Returns:
x, y coordinates and height and width of the current window.
- Example:
driver.get_window_rect()
- set_window_rect(x=None, y=None, width=None, height=None) dict[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)
- property file_detector: FileDetector¶
- property orientation: dict¶
Gets the current orientation of the device.
- Example:
orientation = driver.orientation
- start_devtools() tuple[Any, WebSocketConnection][source]¶
- 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 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 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”) ```
- 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 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]) ```
- 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) ```
- add_virtual_authenticator(options: VirtualAuthenticatorOptions) None[source]¶
Adds a virtual authenticator with the given options.
- property virtual_authenticator_id: str | None¶
Returns the id of the virtual authenticator.
- remove_virtual_authenticator() None[source]¶
Removes a previously added virtual authenticator.
The authenticator is no longer valid after removal, so no methods may be called.
- add_credential(credential: Credential) None[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) ```
- get_credentials() list[Credential][source]¶
Returns the list of credentials owned by the authenticator.
- remove_credential(credential_id: str | bytearray) None[source]¶
Removes a credential from the authenticator.
- Example:
credential_id = “user@example.com” driver.remove_credential(credential_id)
- set_user_verified(verified: bool) None[source]¶
Set whether the authenticator will simulate success or failure on user verification.
- Args:
- verified: True if the authenticator will pass user verification,
False otherwise.
- Example:
driver.set_user_verified(True)
- download_file(file_name: str, target_directory: str) None[source]¶
Download a file with the specified file name to the target directory.
- Args:
file_name: The name of the file to download. target_directory: The path to the directory to save the downloaded file.
- Example:
driver.download_file(“example.zip”, “/path/to/directory”)
- 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()
- property supports_fedcm: bool¶
Returns whether the browser supports FedCM capabilities.
- fedcm_dialog(timeout=5, poll_frequency=0.5, ignored_exceptions=None)[source]¶
Waits for and returns the FedCM dialog.
- Args:
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.