Note
This is not an official documentation. Official API documentation is available here.
This chapter covers all the interfaces of Selenium WebDriver.
Recommended Import Style
The API definitions in this chapter show the absolute location of classes. However, the recommended import style is as given below:
from selenium import webdriver
Then, you can access the classes like this:
webdriver.Firefox webdriver.FirefoxProfile webdriver.FirefoxOptions webdriver.FirefoxService webdriver.Chrome webdriver.ChromeOptions webdriver.ChromeService webdriver.Ie webdriver.IeOptions webdriver.IeService webdriver.Edge webdriver.ChromiumEdge webdriver.EdgeOptions webdriver.EdgeService webdriver.Safari webdriver.SafariOptions webdriver.SafariService webdriver.WebKitGTK webdriver.WebKitGTKOptions webdriver.WebKitGTKService webdriver.WPEWebKit webdriver.WPEWebKitOptions webdriver.WPEWebKitService webdriver.Remote webdriver.DesiredCapabilities webdriver.ActionChains webdriver.Proxy webdriver.Keys
The special keys class (Keys
) can be imported like this:
from selenium.webdriver.common.keys import Keys
The exception classes can be imported like this (Replace the TheNameOfTheExceptionClass
with the actual class name given below):
from selenium.common.exceptions import [TheNameOfTheExceptionClass]
Conventions used in the API
Some attributes are callable (or methods) and others are non-callable (properties). All the callable attributes are ending with round brackets.
Here is an example for property:
current_url
URL of the currently loaded page.
Usage:
Here is an example of a method:
7.1. Exceptions¶
close()
Closes the current window.
Usage:
Exceptions that may happen in all the webdriver code.
Bases: WebDriverException
The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested to be clicked.
Bases: InvalidElementStateException
Thrown when an element is present in the DOM but interactions with that element will hit another element due to paint order.
Bases: InvalidElementStateException
Thrown when trying to select an unselectable element.
For example, selecting a ‘script’ element.
Bases: InvalidElementStateException
Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with.
Most commonly encountered when trying to click or read text of an element that is hidden from view.
Bases: WebDriverException
Thrown when activating an IME engine has failed.
Bases: WebDriverException
Thrown when IME support is not available.
This exception is thrown for every IME-related method call if IME support is not available on the machine.
Bases: WebDriverException
Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate.
Bases: WebDriverException
The arguments passed to a command are either invalid or malformed.
Bases: WebDriverException
Thrown when attempting to add a cookie under a different domain than the current URL.
Bases: WebDriverException
The coordinates provided to an interaction’s operation are invalid.
Bases: WebDriverException
Thrown when a command could not be completed because the element is in an invalid state.
This can be caused by attempting to clear an element that isn’t both editable and resettable.
Bases: WebDriverException
Thrown when the selector which is used to find an element does not return a WebElement.
Currently this only happens when the selector is an xpath expression and it is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).
Bases: WebDriverException
Occurs if the given session id is not in the list of active sessions, meaning the session either does not exist or that it’s not active.
Bases: WebDriverException
Thrown when frame or window target to be switched doesn’t exist.
Bases: WebDriverException
An error occurred while executing JavaScript supplied by the user.
Bases: WebDriverException
Thrown when the target provided to the ActionsChains move() method is invalid, i.e. out of document.
Bases: WebDriverException
Thrown when switching to no presented alert.
This can be caused by calling an operation on the Alert() class when an alert is not yet on the screen.
Bases: WebDriverException
Thrown when the attribute of element could not be found.
You may want to check if the attribute exists in the particular browser you are testing against. Some browsers may have different property names for the same property. (IE8’s .innerText vs. Firefox .textContent)
Bases: WebDriverException
No cookie matching the given path name was found amongst the associated cookies of the current browsing context’s active document.
Bases: WebDriverException
Raised when driver is not specified and cannot be located.
Bases: WebDriverException
Thrown when element could not be found.
Check your selector used in your find_by…
Element may not yet be on the screen at the time of the find operation, (webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait() for how to write a wait wrapper to wait for an element to appear.
Bases: InvalidSwitchToTargetException
Thrown when frame target to be switched doesn’t exist.
Bases: WebDriverException
Thrown when trying to access the shadow root of an element when it does not have a shadow root attached.
Bases: InvalidSwitchToTargetException
Thrown when window target to be switched doesn’t exist.
To find the current set of active window handles, you can get a list of the active window handles in the following way:
print driver.window_handles
Bases: WebDriverException
A screen capture was made impossible.
Bases: WebDriverException
A new session could not be created.
Bases: WebDriverException
Thrown when a reference to an element is now “stale”.
Stale means the element no longer appears on the DOM of the page.
You are no longer on the same page, or the page may have refreshed since the element was located.
The element may have been removed and re-added to the screen, since it was located. Such as an element being relocated. This can happen typically with a javascript framework when values are updated and the node is rebuilt.
Element may have been inside an iframe or another context which was refreshed.
Bases: WebDriverException
Thrown when a command does not complete in enough time.
Bases: WebDriverException
Thrown when a driver fails to set a cookie.
Bases: WebDriverException
Thrown when an unexpected alert has appeared.
Usually raised when an unexpected modal is blocking the webdriver from executing commands.
Bases: WebDriverException
Thrown when a support class did not get an expected web element.
Bases: WebDriverException
The requested command matched a known URL but did not match any methods for that URL.
Bases: Exception
Base webdriver exception.
The ActionChains implementation.
Bases: object
ActionChains are a way to automate low level interactions such as mouse movements, mouse button actions, key press, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop.
When you call methods for actions on the ActionChains object, the actions are stored in a queue in the ActionChains object. When you call perform(), the events are fired in the order they are queued up.
ActionChains can be used in a chain pattern:
menu = driver.find_element(By.CSS_SELECTOR, ".nav") hidden_submenu = driver.find_element(By.CSS_SELECTOR, ".nav #submenu1") ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
Or actions can be queued up one by one, then performed.:
menu = driver.find_element(By.CSS_SELECTOR, ".nav") hidden_submenu = driver.find_element(By.CSS_SELECTOR, ".nav #submenu1") actions = ActionChains(driver) actions.move_to_element(menu) actions.click(hidden_submenu) actions.perform()
Either way, the actions are performed in the order they are called, one after another.
Creates a new ActionChains.
driver: The WebDriver instance which performs user actions.
duration: override the default 250 msecs of DEFAULT_MOVE_DURATION in PointerInput
Clicks an element.
on_element: The element to click. If None, clicks on current mouse position.
Holds down the left mouse button on an element.
on_element: The element to mouse down. If None, clicks on current mouse position.
Performs a context-click (right click) on an element.
on_element: The element to context-click. If None, clicks on current mouse position.
Double-clicks an element.
on_element: The element to double-click. If None, clicks on current mouse position.
Holds down the left mouse button on the source element, then moves to the target element and releases the mouse button.
source: The element to mouse down.
target: The element to mouse up.
Holds down the left mouse button on the source element, then moves to the target offset and releases the mouse button.
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
Sends a key press only, without releasing it. Should only be used with modifier keys (Control, Alt and Shift).
value: The modifier key to send. Values are defined in Keys class.
element: The element to send keys. If None, sends a key to current focused element.
Example, pressing ctrl+c:
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
Releases a modifier key.
value: The modifier key to send. Values are defined in Keys class.
element: The element to send keys. If None, sends a key to current focused element.
Example, pressing ctrl+c:
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
Moving the mouse to an offset from current mouse position.
xoffset: X offset to move to, as a positive or negative integer.
yoffset: Y offset to move to, as a positive or negative integer.
Moving the mouse to the middle of an element.
to_element: The WebElement to move to.
Move the mouse by an offset of the specified element. Offsets are relative to the in-view center point of the element.
to_element: The WebElement to move to.
xoffset: X offset to move to, as a positive or negative integer.
yoffset: Y offset to move to, as a positive or negative integer.
Pause all inputs for the specified duration in seconds.
Performs all stored actions.
Releasing a held mouse button on an element.
on_element: The element to mouse up. If None, releases on current mouse position.
Clears actions that are already stored locally and on the remote end.
Scrolls by provided amounts with the origin in the top left corner of the viewport.
delta_x: Distance along X axis to scroll using the wheel. A negative value scrolls left.
delta_y: Distance along Y axis to scroll using the wheel. A negative value scrolls up.
Scrolls by provided amount based on a provided origin. The scroll origin is either the center of an element or the upper left of the viewport plus any offsets. If the origin is an element, and the element is not in the viewport, the bottom of the element will first be scrolled to the bottom of the viewport.
origin: Where scroll originates (viewport or element center) plus provided offsets.
delta_x: Distance along X axis to scroll using the wheel. A negative value scrolls left.
delta_y: Distance along Y axis to scroll using the wheel. A negative value scrolls up.
If the origin with offset is outside the viewport. - MoveTargetOutOfBoundsException - If the origin with offset is outside the viewport.
If the element is outside the viewport, scrolls the bottom of the element to the bottom of the viewport.
element: Which element to scroll into the viewport.
Sends keys to current focused element.
keys_to_send: The keys to send. Modifier keys constants can be found in the ‘Keys’ class.
Sends keys to an element.
element: The element to send keys.
keys_to_send: The keys to send. Modifier keys constants can be found in the ‘Keys’ class.
The Alert implementation.
Bases: object
Allows to work with alerts.
Use this class to interact with alert prompts. It contains methods for dismissing, accepting, inputting, and getting text from alert prompts.
Accepting / Dismissing alert prompts:
Alert(driver).accept() Alert(driver).dismiss()
Inputting a value into an alert prompt:
name_prompt = Alert(driver) name_prompt.send_keys("Willian Shakesphere") name_prompt.accept()
Reading a the text of a prompt for verification:
alert_text = Alert(driver).text self.assertEqual("Do you wish to quit?", alert_text)
Creates a new Alert.
driver: The WebDriver instance which performs user actions.
Accepts the alert available.
Alert(driver).accept() # Confirm a alert dialog.
Dismisses the alert available.
Send Keys to the Alert.
keysToSend: The text to be sent to Alert.
Gets the text of the Alert.
The Keys implementation.
Bases: object
Set of special keys codes.
These are the attributes which can be used to locate elements. See the Locating Elements chapter for example usages.
The By implementation.
Bases: object
Set of supported locator strategies.
See the Using Selenium with remote WebDriver section for example usages of desired capabilities.
The Desired Capabilities implementation.
Bases: object
Set of default supported desired capabilities.
Use this as a starting point for creating a desired capabilities object for requesting remote webdrivers for connecting to selenium server or selenium grid.
Usage Example:
from selenium import webdriver selenium_grid_url = "http://198.0.0.1:4444/wd/hub" # Create a desired capabilities object as a starting point. capabilities = DesiredCapabilities.FIREFOX.copy() capabilities['platform'] = "WINDOWS" capabilities['version'] = "10" # Instantiate an instance of Remote WebDriver with the desired capabilities. driver = webdriver.Remote(desired_capabilities=capabilities, command_executor=selenium_grid_url)
Note: Always use ‘.copy()’ on the DesiredCapabilities object to avoid the side effects of altering the Global class instance.
The Proxy implementation.
Bases: object
Proxy contains information about proxy type and necessary proxy settings.
Creates a new Proxy.
raw: raw proxy data. If None, default class values are used.
Gets and Sets auto_detect
7. Usage¶self.auto_detect
self.auto_detect = value
value: str
Gets and Sets ftp_proxy
7. Usage¶self.ftp_proxy
self.ftp_proxy = value
value: str
Gets and Sets http_proxy
7. Usage¶self.http_proxy
self.http_proxy = value
value: str
Gets and Sets no_proxy
7. Usage¶self.no_proxy
self.no_proxy = value
value: str
Gets and Sets proxy_autoconfig_url
7. Usage¶self.proxy_autoconfig_url
self.proxy_autoconfig_url = value
value: str
Returns proxy type as ProxyType.
Gets and Sets socks_password
7. Usage¶self.socks_password
self.socks_password = value
value: str
Gets and Sets socks_proxy
7. Usage¶self.sock_proxy
self.socks_proxy = value
value: str
Gets and Sets socks_password
7. Usage¶self.socks_password
self.socks_password = value
value: str
Gets and Sets socks_version
7. Usage¶self.socks_version
self.socks_version = value
value: str
Gets and Sets ssl_proxy
7. Usage¶self.ssl_proxy
self.ssl_proxy = value
value: str
Bases: object
Set of possible types of proxy.
Each proxy type has 2 properties: ‘ff_value’ is value of Firefox profile preference, ‘string’ is id of proxy type.
Bases: object
Factory for proxy types.
The Utils methods.
Resolve a hostname to an IP, preferring IPv4 addresses.
We prefer IPv4 so that we don’t change behavior from previous IPv4-only implementations, and because some drivers (e.g., FirefoxDriver) do not support IPv6 connections.
If the optional port number is provided, only IPs that listen on the given port are considered.
host - A hostname.
port - Optional port number.
A single IP address, as a string. If any IPv4 address is found, one is returned. Otherwise, if any IPv6 address is found, one is returned. If neither, then None is returned.
Determines a free port using sockets.
Tries to connect to the server at port to see if it is running.
port - The port to connect.
Tries to connect to the HTTP server at /status path and specified port to see if it responds successfully.
port - The port to connect.
Joins a hostname and port together.
This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port(‘::1’, 80) == ‘[::1]:80’.
host - A hostname.
port - An integer port.
Processes the values that will be typed in the element.
Bases: ABC
The abstract base class for all service objects. Services typically launch a child program in a new process as an interim process to communicate with a browser.
executable – install path of the executable.
port – Port for the service to run on, defaults to 0 where the operating system will decide.
log_output – (Optional) int representation of STDOUT/DEVNULL, any IO instance or String path to file.
env – (Optional) Mapping of environment variables for the new process, defaults to os.environ.
Check if the underlying process is still running.
A List of program arguments (excluding the executable).
Establishes a socket connection to determine if the service running on the port is accessible.
Dispatch an HTTP request to the shutdown endpoint for the service in an attempt to stop it.
Starts the Service.
WebDriverException : Raised either when it can’t start the service or when it can’t connect to the service
Stops the service.
Gets the url of the Service.
Bases: WebDriver
Controls the GeckoDriver and allows you to drive the browser.
Creates a new instance of the Firefox driver. Starts the service and then creates new instance of Firefox driver.
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.
Sets 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.
context – Context, may be one of the class properties CONTEXT_CHROME or CONTEXT_CONTENT.
Usage example:
with selenium.context(selenium.CONTEXT_CHROME): # chrome scope ... do stuff ...
Gets the full document screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML.
driver.get_full_page_screenshot_as_base64()
Saves a full document 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.
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
driver.get_full_page_screenshot_as_file('/Screenshots/foo.png')
Gets the full document screenshot of the current window as a binary data.
driver.get_full_page_screenshot_as_png()
Installs Firefox addon.
Returns identifier of installed addon. This identifier can later be used to uninstall addon.
temporary – allows you to load browser extensions temporarily during a session
path – Absolute path to the addon that will be installed.
driver.install_addon('/path/to/firebug.xpi')
Closes the browser and shuts down the GeckoDriver executable.
Saves a full document 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.
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
driver.save_full_page_screenshot('/Screenshots/foo.png')
Uninstalls Firefox addon using its identifier.
driver.uninstall_addon('addon@foo.com')
Bases: object
Bases: ArgOptions
Enables mobile browser use for browsers that support it.
android_activity: The name of the android package to start
Sets a preference.
Marshals the Firefox options to a moz:firefoxOptions object.
Returns the FirefoxBinary instance.
The location of the binary.
Return minimal capabilities necessary as a dictionary.
A dict of preferences.
The Firefox profile to use.
Bases: Exception
Exception for not well-formed add-on manifest files.
Bases: object
Initialises a new instance of a Firefox Profile.
profile_directory: Directory of profile that you want to use. If a directory is passed in it will be cloned and the cloned directory will be used by the driver when instantiated. This defaults to None and will create a new directory when object is created.
Sets the preference that we want in the profile.
Writes the desired user prefs to disk.
Updates preferences and creates a zipped, base64 encoded string of profile directory.
Gets the profile directory that is currently being used.
Gets the port that WebDriver is working on.
Bases: object
Creates a new instance of Firefox binary.
firefox_path - Path to the Firefox executable. By default, it will be detected from the standard locations.
Please note that with parallel run the output won’t be synchronous. By default, it will be redirected to /dev/null.
Kill the browser.
This is useful when the browser is stuck.
Launches the browser for the given profile name.
It is assumed the profile already exists.
Returns the fully qualified path by searching Path of the given name.
Bases: ChromiumDriver
Controls the ChromeDriver and allows you to drive the browser.
Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver.
options - this takes an instance of ChromeOptions
service - Service object for handling the browser driver if you need to pass extra details
keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
Bases: ChromiumOptions
Enables mobile browser use for browsers that support it.
android_activity: The name of the android package to start
Return minimal capabilities necessary as a dictionary.
Bases: ChromiumService
A Service class that is responsible for the starting and stopping of chromedriver.
executable_path – install path of the chromedriver executable, defaults to chromedriver.
port – Port for the service to run on, defaults to 0 where the operating system will decide.
service_args – (Optional) List of args to be passed to the subprocess when launching the executable.
log_output – (Optional) int representation of STDOUT/DEVNULL, any IO instance or String path to file.
env – (Optional) Mapping of environment variables for the new process, defaults to os.environ.
The WebDriver implementation.
Bases: object
Abstract Base Class for all Webdriver subtypes.
ABC’s allow custom implementations of Webdriver to be registered so that isinstance type checks will succeed.
Bases: BaseWebDriver
Controls a browser by sending commands to a remote server. This server is expected to be running the WebDriver wire protocol as defined at https://www.selenium.dev/documentation/legacy/json_wire_protocol/.
session_id - String ID of the browser session started and controlled by this WebDriver.
by the remote server. See https://www.selenium.dev/documentation/legacy/desired_capabilities/
command_executor - remote_connection.RemoteConnection object used to execute commands.
error_handler - errorhandler.ErrorHandler object used to handle errors.
Create a new driver that will issue commands using the wire protocol.
remote_connection.RemoteConnection object. Defaults to ‘http://127.0.0.1:4444/wd/hub’.
HTTP keep-alive. Defaults to True.
then default LocalFileDetector() will be used.
options - instance of a driver options.Options class
Adds a cookie to your current session.
optional keys - “path”, “domain”, “secure”, “httpOnly”, “expiry”, “sameSite”
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'})
Injects a credential into the authenticator.
Adds a virtual authenticator with the given options.
Goes one step backward in the browser history.
Closes the current window.
Creates a web element with the specified element_id.
Delete all cookies in the scope of the session.
driver.delete_all_cookies()
Deletes a single cookie with the given name.
driver.delete_cookie('my_cookie')
Deletes all downloadable files.
Downloads a file with the specified file name to the target directory.
file_name: The name of the file to download. target_directory: The path to the directory to save the downloaded file.
Sends a command to be executed by a command.CommandExecutor.
driver_command: The name of the command to execute as a string.
params: A dictionary of named parameters to send with the command.
The command’s JSON response loaded into a dictionary object.
Asynchronously Executes JavaScript in the current window/frame.
script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript.
script = "var callback = arguments[arguments.length - 1]; " \ "window.setTimeout(function(){ callback('timeout') }, 3000);" driver.execute_async_script(script)
Synchronously Executes JavaScript in the current window/frame.
script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript.
driver.execute_script('return document.title;')
Overrides the current file detector (if necessary) in limited context. Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector): someinput.send_keys('/etc/hosts')
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.
instantiation.
kwargs - Keyword arguments, passed the same way as args.
Find an element given a By strategy and locator.
element = driver.find_element(By.ID, 'foo')
Find elements given a By strategy and locator.
elements = driver.find_elements(By.CLASS_NAME, 'foo')
list of WebElement
Goes one step forward in the browser history.
Invokes the window manager-specific ‘full screen’ operation.
Loads a web page in the current browser session.
Get a single cookie by name. Returns the cookie if found, None if not.
driver.get_cookie('my_cookie')
Returns a set of dictionaries, corresponding to cookies visible in the current session.
Returns the list of credentials owned by the authenticator.
Retrieves the downloadable files as a map of file names and their corresponding URLs.
Gets the log for a given log type.
log_type: type of log that which will be returned
driver.get_log('browser') driver.get_log('driver') driver.get_log('client') driver.get_log('server')
Gets the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML.
driver.get_screenshot_as_base64()
Saves 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.
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
driver.get_screenshot_as_file('/Screenshots/foo.png')
Gets the screenshot of the current window as a binary data.
driver.get_screenshot_as_png()
Gets the x,y position of the current window.
driver.get_window_position()
Gets the x, y coordinates of the window as well as height and width of the current window.
Gets the width and height of the current window.
Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout.
time_to_wait: Amount of time to wait (in seconds)
driver.implicitly_wait(30)
Maximizes the current window that webdriver is using.
Invokes the window manager-specific ‘minimize’ operation.
Store common javascript scripts to be executed later by a unique hashable ID.
Takes PDF of the current page.
The driver makes a best effort to return a PDF based on the provided parameters.
Quits the driver and closes every associated window.
Refreshes the current page.
Removes all credentials from the authenticator.
Removes a credential from the authenticator.
Removes a previously added virtual authenticator.
The authenticator is no longer valid after removal, so no methods may be called.
Saves 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.
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
driver.save_screenshot('/Screenshots/foo.png')
Set the amount of time to wait for a page load to complete before throwing an error.
time_to_wait: The amount of time to wait
driver.set_page_load_timeout(30)
Set the amount of time that the script should wait during an execute_async_script call before throwing an error.
time_to_wait: The amount of time to wait (in seconds)
driver.set_script_timeout(30)
Sets whether the authenticator will simulate success or fail on user verification.
verified: True if the authenticator will pass user verification, False otherwise.
Sets the x,y position of the current window. (window.moveTo)
x: the x-coordinate in pixels to set the window position
y: the y-coordinate in pixels to set the window position
driver.set_window_position(0,0)
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.
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)
Sets the width and height of the current window. (window.resizeTo)
width: the width in pixels to set the window to
height: the height in pixels to set the window to
driver.set_window_size(800,600)
Called before starting a new session.
This method may be overridden to define custom startup behavior.
Creates a new session with the desired capabilities.
capabilities - a capabilities dict to start the session with.
Called after executing a quit command.
This method may be overridden to define custom shutdown behavior.
Remove a pinned script from storage.
Returns the drivers current capabilities being used.
Gets the URL of the current page.
Returns the handle of the current window.
driver.current_window_handle
Gets a list of the available log types. This only works with w3c compliant browsers.
Returns the name of the underlying browser for this instance.
Gets the current orientation of the device.
orientation = driver.orientation
Gets the source of the current page.
SwitchTo: an object containing all options to switch focus into
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 all the timeouts that have been set on the current session.
Timeout
Returns the title of the current page.
Returns the id of the virtual authenticator.
Returns the handles of all windows within the current session.
Bases: object
Abstract Base Class for WebElement.
ABC’s will allow custom types to be registered as a WebElement to pass type checks.
Bases: BaseWebElement
Represents a DOM element.
Generally, all interesting operations that interact with a document will be performed through this interface.
All method calls will do a freshness check to ensure that the element reference is still valid. This essentially determines whether the element is still attached to the DOM. If this test fails, then an StaleElementReferenceException
is thrown, and all future calls to this instance will fail.
Clears the text if it’s a text entry element.
Clicks the element.
Find an element given a By strategy and locator.
element = element.find_element(By.ID, 'foo')
Find elements given a By strategy and locator.
element = element.find_elements(By.CLASS_NAME, 'foo')
list of WebElement
Gets the given attribute or property of the element.
This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that name, None
is returned.
Values which are considered truthy, that is equals “true” or “false”, are returned as booleans. All other non-None
values are returned as strings. For attributes or properties which do not exist, None
is returned.
To obtain the exact value of the attribute or property, use get_dom_attribute()
or get_property()
methods respectively.
name - Name of the attribute/property to retrieve.
Example:
# Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class")
Gets the given attribute of the element. Unlike get_attribute()
, this method only returns attributes declared in the element’s HTML markup.
name - Name of the attribute to retrieve.
text_length = target_element.get_dom_attribute("class")
Gets the given property of the element.
name - Name of the property to retrieve.
text_length = target_element.get_property("text_length")
Whether the element is visible to a user.
Returns whether the element is enabled.
Returns whether the element is selected.
Can be used to check if a checkbox or radio button is selected.
Saves a screenshot of the current element to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename.
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
element.screenshot('/Screenshots/foo.png')
Simulates typing into the element.
value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path.
Use this to send simple key events or to fill out form fields:
form_textfield = driver.find_element(By.NAME, 'username') form_textfield.send_keys("admin")
This can also be used to set file inputs.
file_input = driver.find_element(By.NAME, 'profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
Submits a form.
The value of a CSS property.
Returns the ARIA Level of the current webelement.
Returns the ARIA role of the current web element.
Internal ID used by selenium.
This is mainly for internal use. Simple use cases such as checking if 2 webelements refer to the same element, can be done using ==
:
if element1 == element2: print("These 2 are equal")
The location of the element in the renderable canvas.
THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.
Returns the top lefthand corner location on the screen, or zero coordinates if the element is not visible.
Internal reference to the WebDriver instance this element was found from.
A dictionary with the size and location of the element.
Gets the screenshot of the current element as a base64 encoded string.
img_b64 = element.screenshot_as_base64
Gets the screenshot of the current element as a binary data.
element_png = element.screenshot_as_png
Returns a shadow root of the element if there is one or an error. Only works from Chromium 96, Firefox 96, and Safari 16.4 onwards.
ShadowRoot object or
NoSuchShadowRoot - if no shadow root was attached to element
The size of the element.
This element’s tagName
property.
The text of the element.
Bases: object
Defines constants for the standard WebDriver commands.
While these constants have no meaning in and of themselves, they are used to marshal commands through a service that implements WebDriver’s remote wire protocol:
Bases: object
Error codes defined in the WebDriver wire protocol.
Bases: object
Handles errors returned by the WebDriver server.
Checks that a JSON response from the WebDriver does not have an error.
response - The JSON response from the WebDriver server as a dictionary object.
If the response contains an error message.
Bases: object
:Maps each errorcode in ErrorCode object to corresponding exception Please refer to https://www.w3.org/TR/webdriver2/#errors for w3c specification
alias of ElementClickInterceptedException
alias of ElementNotSelectableException
alias of ElementNotInteractableException
alias of ElementNotVisibleException
alias of ImeActivationFailedException
alias of ImeNotAvailableException
alias of InsecureCertificateException
alias of InvalidArgumentException
alias of InvalidCookieDomainException
alias of InvalidCoordinatesException
alias of InvalidElementStateException
alias of InvalidSelectorException
alias of InvalidSessionIdException
alias of InvalidSelectorException
alias of InvalidSelectorException
alias of JavascriptException
alias of MoveTargetOutOfBoundsException
alias of NoAlertPresentException
alias of NoSuchCookieException
alias of NoSuchElementException
alias of NoSuchFrameException
alias of NoSuchShadowRootException
alias of NoSuchWindowException
alias of TimeoutException
alias of SessionNotCreatedException
alias of StaleElementReferenceException
alias of TimeoutException
alias of ScreenshotException
alias of UnableToSetCookieException
alias of UnexpectedAlertPresentException
alias of WebDriverException
alias of UnknownMethodException
Bases: object
alias of _ConnectionType
Set the network connection for the remote device.
Example of setting airplane mode:
driver.mobile.set_network_connection(driver.mobile.AIRPLANE_MODE)
Returns the current context (Native or WebView).
Returns a list of available contexts.
Bases: object
A connection with the Remote WebDriver server.
Communicates with the server using the WebDriver wire protocol: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
Clean up resources when finished with the remote_connection.
Send a command to the remote server.
Any path substitutions required for the URL mapped to the command should be included in the command parameters.
command - A string specifying the command to execute.
params - A dictionary of named parameters to send with the command as its JSON payload.
Paths of the .pem encoded certificate to verify connection to command executor. Defaults to certifi.where() or REQUESTS_CA_BUNDLE env variable if set.
Get headers for remote request.
parsed_url - The parsed url
keep_alive (Boolean) - Is this a keep-alive connection (default: False)
Timeout value in seconds for all http requests made to the Remote Connection
Reset the http request timeout to socket._GLOBAL_DEFAULT_TIMEOUT.
Set the path to the certificate bundle to verify connection to command executor. Can also be set to None to disable certificate validation.
path - path of a .pem encoded certificate chain.
Override the default timeout.
timeout - timeout value for http requests in seconds
Bases: WebDriver
Controls the IEServerDriver and allows you to drive Internet Explorer.
Creates a new instance of the Ie driver.
Starts the service and then creates new instance of Ie driver.
options - IE Options instance, providing additional IE options
service - (Optional) service instance for managing the starting and stopping of the driver.
keep_alive - Whether to configure RemoteConnection to use HTTP keep-alive.
Closes the browser and shuts down the IEServerDriver executable.
Bases: WebDriver
Controls the SafariDriver and allows you to drive the browser.
Creates a new Safari driver instance and launches or finds a running safaridriver service.
HTTP keep-alive. Defaults to True.
options - Instance of options.Options
.
service - Service object for handling the browser driver if you need to pass extra details
Closes the browser and shuts down the SafariDriver executable.
Bases: Service
A Service class that is responsible for the starting and stopping of safaridriver This is only supported on MAC OSX.
executable_path – install path of the safaridriver executable, defaults to /usr/bin/safaridriver.
port – Port for the service to run on, defaults to 0 where the operating system will decide.
service_args – (Optional) List of args to be passed to the subprocess when launching the executable.
env – (Optional) Mapping of environment variables for the new process, defaults to os.environ.
A List of program arguments (excluding the executable).
Gets the url of the SafariDriver Service.
Bases: object
Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not, then an UnexpectedTagNameException is thrown.
webelement - SELECT element to wrap
from selenium.webdriver.support.ui import Select
Select(driver.find_element(By.TAG_NAME, “select”)).select_by_index(2)
Clear all selected entries.
This is only valid when the SELECT supports multiple selections. throws NotImplementedError If the SELECT does not support multiple selections
Deselect the option at the given index. This is done by examining the “index” attribute of an element, and not merely by counting.
index - The option at this index will be deselected
throws NoSuchElementException If there is no option with specified index in SELECT
Deselect all options that have a value matching the argument. That is, when given “foo” this would deselect an option like:
<option value=”foo”>Bar</option>
value - The value to match against
throws NoSuchElementException If there is no option with specified value in SELECT
Deselect all options that display text matching the argument. That is, when given “Bar” this would deselect an option like:
<option value=”foo”>Bar</option>
text - The visible text to match against
Select the option at the given index. This is done by examining the “index” attribute of an element, and not merely by counting.
index - The option at this index will be selected
throws NoSuchElementException If there is no option with specified index in SELECT
Select all options that have a value matching the argument. That is, when given “foo” this would select an option like:
<option value=”foo”>Bar</option>
value - The value to match against
throws NoSuchElementException If there is no option with specified value in SELECT
Select all options that display text matching the argument. That is, when given “Bar” this would select an option like:
<option value=”foo”>Bar</option>
text - The visible text to match against
throws NoSuchElementException If there is no option with specified text in SELECT
Returns a list of all selected options belonging to this select tag.
The first selected option in this select tag (or the currently selected option in a normal select)
Returns a list of all options belonging to this select tag.
Bases: Generic
[D
]
Constructor, takes a WebDriver instance and timeout in seconds.
driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) or a WebElement
timeout - Number of seconds before timing out
poll_frequency - sleep interval between calls By default, it is 0.5 second.
ignored_exceptions - iterable structure of exception classes ignored during calls. By default, it contains NoSuchElementException only.
Example:
from selenium.webdriver.support.wait import WebDriverWait element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, "someId")) is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ until_not(lambda x: x.find_element(By.ID, "someId").is_displayed())
Calls the method provided with the driver as an argument until the return value does not evaluate to False
.
method – callable(WebDriver)
message – optional message for TimeoutException
the result of the last call to method
selenium.common.exceptions.TimeoutException
if timeout occurs
Calls the method provided with the driver as an argument until the return value evaluates to False
.
method – callable(WebDriver)
message – optional message for TimeoutException
the result of the last call to method, or True
if method has raised one of the ignored exceptions
selenium.common.exceptions.TimeoutException
if timeout occurs
Bases: object
Color conversion support class.
Example:
from selenium.webdriver.support.color import Color print(Color.from_string('#00ff33').rgba) print(Color.from_string('rgb(1, 255, 3)').hex) print(Color.from_string('blue').rgba)
Bases: object
A wrapper around an arbitrary WebDriver instance which supports firing events.
Creates a new instance of the EventFiringWebDriver.
driver : A WebDriver instance
event_listener : Instance of a class that subclasses AbstractEventListener and implements it fully or partially
Example:
from selenium.webdriver import Firefox from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener class MyListener(AbstractEventListener): def before_navigate_to(self, url, driver): print("Before navigate to %s" % url) def after_navigate_to(self, url, driver): print("After navigate to %s" % url) driver = Firefox() ef_driver = EventFiringWebDriver(driver, MyListener()) ef_driver.get("http://www.google.co.in/")
Returns the WebDriver instance wrapped by this EventsFiringWebDriver.
Bases: object
A wrapper around WebElement instance which supports firing events.
Creates a new instance of the EventFiringWebElement.
Returns the WebElement wrapped by this EventFiringWebElement instance.
Bases: object
Event listener must subclass and implement this fully or partially.
An expectation for checking if an alert is currently present and switching to it.
An expectation that all of multiple expected conditions is true.
Equivalent to a logical ‘AND’. Returns: When any ExpectedCondition is not met: False. When all ExpectedConditions are met: A List with each ExpectedCondition’s return value.
An expectation that any of multiple expected conditions is true.
Equivalent to a logical ‘OR’. Returns results of the first matching condition, or False if none do.
An expectation for checking if the given attribute is included in the specified element.
locator, attribute
An expectation to locate an element and check if the selection state specified is in that state.
locator is a tuple of (by, path) is_selected is a boolean
An expectation for the element to be located is selected.
locator is a tuple of (by, path)
An expectation for checking if the given element is selected.
element is WebElement object is_selected is a Boolean.
An Expectation for checking an element is visible and enabled such that you can click it.
element is either a locator (text) or an WebElement
An expectation for checking the selection is selected.
element is WebElement object
An expectation for checking whether the given frame is available to switch to.
If the frame is available it switches the given driver to the specified frame.
An Expectation for checking that an element is either invisible or not present on the DOM.
element is either a locator (text) or an WebElement
An Expectation for checking that an element is either invisible or not present on the DOM.
locator used to find the element
An expectation that a new window will be opened and have the number of windows handles increase.
An expectation that none of 1 or multiple expected conditions is true.
Equivalent to a logical ‘NOT-OR’. Returns a Boolean
An expectation for the number of windows to be a certain value.
An expectation for checking that there is at least one element present on a web page.
locator is used to find the element returns the list of WebElements once they are located
An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.
locator - used to find the element returns the WebElement once it is located
Wait until an element is no longer attached to the DOM.
element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise.
An expectation for checking if the given text is present in the specified element.
locator, text
An expectation for checking if the given text is present in the element’s attribute.
locator, attribute, text
An expectation for checking if the given text is present in the element’s value.
locator, text
An expectation for checking that the title contains a case-sensitive substring.
title is the fragment of title expected returns True when the title matches, False otherwise
An expectation for checking the title of a page.
title is the expected title, which must be an exact match returns True if the title matches, false otherwise.
An expectation for checking the current url.
url is the expected url, which must not be an exact match returns True if the url is different, false otherwise.
An expectation for checking that the current url contains a case- sensitive substring.
url is the fragment of url expected, returns True when the url matches, False otherwise
An expectation for checking the current url.
pattern is the expected pattern. This finds the first occurrence of pattern in the current url and as such does not require an exact full match.
An expectation for checking the current url.
url is the expected url, which must be an exact match returns True if the url matches, false otherwise.
An expectation for checking that an element, known to be present on the DOM of a page, is visible.
Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same) WebElement once it is visible
An expectation for checking that all elements are present on the DOM of a page and visible. Visibility means that the elements are not only displayed but also has a height and width that is greater than 0.
locator - used to find the elements returns the list of WebElements once they are located and visible
An expectation for checking that there is at least one element visible on a web page.
locator is used to find the element returns the list of WebElements once they are located
An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.
locator - used to find the element returns the WebElement once it is located and visible
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4