selenium.webdriver.firefox.webdriver

Classes

WebDriver([options, service, keep_alive])

Controls the GeckoDriver and allows you to drive the browser.

class selenium.webdriver.firefox.webdriver.WebDriver(options: Options | None = None, service: Service | None = None, keep_alive: bool = True)[source]

Controls the GeckoDriver and allows you to drive the browser.

Create a new instance of the Firefox driver, start the service, and create new instance.

Args:

options: Instance of options.Options. service: (Optional) service instance for managing the starting and stopping of the driver. keep_alive: Whether to configure remote_connection.RemoteConnection to use HTTP keep-alive.

CONTEXT_CHROME = 'chrome'
CONTEXT_CONTENT = 'content'
quit() None[source]

Closes the browser and shuts down the GeckoDriver executable.

set_context(context) None[source]

Sets the context that Selenium commands are running in.

Args:

context: Context to set, should be one of CONTEXT_CHROME or CONTEXT_CONTENT.

context(context)[source]

Set the context that Selenium commands are running in using a with statement.

The state of the context on the server is saved before entering the block, and restored upon exiting it.

Args:
context: Context, may be one of the class properties

CONTEXT_CHROME or CONTEXT_CONTENT.

Example:
with selenium.context(selenium.CONTEXT_CHROME):

# chrome scope … do stuff …

install_addon(path, temporary=False) str[source]

Installs Firefox addon.

Returns identifier of installed addon. This identifier can later be used to uninstall addon.

Args:

path: Absolute path to the addon that will be installed. temporary: Allows you to load browser extensions temporarily during a session.

Returns:

Identifier of installed addon.

Example:

driver.install_addon(“/path/to/firebug.xpi”)

uninstall_addon(identifier) None[source]

Uninstalls Firefox addon using its identifier.

Args:

identifier: The addon identifier to uninstall.

Example:

driver.uninstall_addon(”addon@foo.com”)

get_full_page_screenshot_as_file(filename) bool[source]

Save a full document screenshot of the current window to a PNG image file.

Args:
filename: The full path you wish to save your screenshot to. This

should end with a .png extension.

Returns:

False if there is any IOError, else returns True. Use full paths in your filename.

Example:

driver.get_full_page_screenshot_as_file(“/Screenshots/foo.png”)

save_full_page_screenshot(filename) bool[source]

Save a full document screenshot of the current window to a PNG image file.

Args:
filename: The full path you wish to save your screenshot to. This

should end with a .png extension.

Returns:

False if there is any IOError, else returns True. Use full paths in your filename.

Example:

driver.save_full_page_screenshot(“/Screenshots/foo.png”)

get_full_page_screenshot_as_png() bytes[source]

Get the full document screenshot of the current window as binary data.

Returns:

Binary data of the screenshot.

Example:

driver.get_full_page_screenshot_as_png()

get_full_page_screenshot_as_base64() str[source]

Get the full document screenshot of the current window as a base64-encoded string.

Returns:

Base64 encoded string of the screenshot.

Example:

driver.get_full_page_screenshot_as_base64()

download_file(*args, **kwargs)[source]

Download file functionality is not implemented for Firefox driver.

get_downloadable_files(*args, **kwargs)[source]

Get downloadable files functionality is not implemented for Firefox driver.

delete_downloadable_files(*args, **kwargs)[source]

Delete downloadable files functionality is not implemented for Firefox driver.

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”})

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) ```

add_virtual_authenticator(options: VirtualAuthenticatorOptions) None[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) ```

back() None[source]

Goes one step backward in the browser history.

bidi_connection()[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 capabilities: dict

Returns the drivers current capabilities being used.

close() None[source]

Closes the current window.

create_web_element(element_id: str) WebElement[source]

Creates a web element with the specified element_id.

property current_url: str

Gets the URL of the current page.

property current_window_handle: str

Returns the handle of the current window.

delete_all_cookies() None[source]

Delete all cookies in the scope of the session.

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”)

property dialog: Dialog

Returns the FedCM dialog object for interaction.

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: 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.

execute_async_script(script: str, *args) dict[source]

Asynchronously Executes JavaScript in the current window/frame.

Args:

script: The javascript to execute. *args: Any applicable arguments for your JavaScript.

Example:

``` script = “var callback = arguments[arguments.length - 1]; “

“window.setTimeout(function(){ callback(‘timeout’) }, 3000);”

driver.execute_async_script(script) ```

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_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) `

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.

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.

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.

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”)

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’)

forward() None[source]

Goes one step forward in the browser history.

fullscreen_window() None[source]

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

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.

Args:
url: The URL to be opened by the browser. Must include the protocol

(e.g., http://, https://).

Example:

driver.get(“https://example.com”)

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”)

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_credentials() list[Credential][source]

Returns the list of credentials owned by the authenticator.

get_pinned_scripts() list[str][source]

Return a list of all pinned scripts.

Example:

pinned_scripts = driver.get_pinned_scripts()

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()

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”)

get_screenshot_as_png() bytes[source]

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

Example:

driver.get_screenshot_as_png()

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()

get_window_size(windowHandle: str = 'current') dict[source]

Gets the width and height of the current window.

Example:

driver.get_window_size()

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)

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) ```

maximize_window() None[source]

Maximizes the current window that webdriver is using.

minimize_window() None[source]

Invokes the window manager-specific ‘minimize’ operation.

property mobile: Mobile
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: 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”

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.

refresh() None[source]

Refreshes the current page.

remove_all_credentials() None[source]

Removes all credentials from 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)

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.

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”)

property script: Script
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)

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_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)

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)

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)

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)

start_client() None[source]

Called before starting a new session.

This method may be overridden to define custom startup behavior.

start_devtools() tuple[Any, WebSocketConnection][source]
start_session(capabilities: dict) None[source]

Creates a new session with the desired capabilities.

Args:

capabilities: A capabilities dict to start the session with.

stop_client() None[source]

Called after executing a quit command.

This method may be overridden to define custom shutdown behavior.

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:
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

property title: str

Returns the title of the current page.

Example:

` element = driver.find_element(By.ID, "foo") print(element.title()) `

unpin(script_key: ScriptKey) None[source]

Remove a pinned script from storage.

Example:

driver.unpin(script_key)

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.