diff --git a/py/selenium/webdriver/common/actions/action_builder.py b/py/selenium/webdriver/common/actions/action_builder.py index 35ef44f570488..e4f923976c7dd 100644 --- a/py/selenium/webdriver/common/actions/action_builder.py +++ b/py/selenium/webdriver/common/actions/action_builder.py @@ -49,14 +49,11 @@ def __init__( def get_device_with(self, name: str) -> Optional[Union["WheelInput", "PointerInput", "KeyInput"]]: """Get the device with the given name. - Parameters: - ----------- - name : str - The name of the device to get. + Args: + name: The name of the device to get. Returns: - -------- - Optional[Union[WheelInput, PointerInput, KeyInput]] : The device with the given name. + The device with the given name, or None if not found. """ return next(filter(lambda x: x == name, self.devices), None) @@ -83,19 +80,15 @@ def wheel_action(self) -> WheelActions: def add_key_input(self, name: str) -> KeyInput: """Add a new key input device to the action builder. - Parameters: - ----------- - name : str - The name of the key input device. + Args: + name: The name of the key input device. Returns: - -------- - KeyInput : The newly created key input device. + The newly created key input device. Example: - -------- - >>> action_builder = ActionBuilder(driver) - >>> action_builder.add_key_input(name="keyboard2") + >>> action_builder = ActionBuilder(driver) + >>> action_builder.add_key_input(name="keyboard2") """ new_input = KeyInput(name) self._add_input(new_input) @@ -104,25 +97,17 @@ def add_key_input(self, name: str) -> KeyInput: def add_pointer_input(self, kind: str, name: str) -> PointerInput: """Add a new pointer input device to the action builder. - Parameters: - ----------- - kind : str - The kind of pointer input device. - - "mouse" - - "touch" - - "pen" - - name : str - The name of the pointer input device. + Args: + kind: The kind of pointer input device. Valid values are "mouse", + "touch", or "pen". + name: The name of the pointer input device. Returns: - -------- - PointerInput : The newly created pointer input device. + The newly created pointer input device. Example: - -------- - >>> action_builder = ActionBuilder(driver) - >>> action_builder.add_pointer_input(kind="mouse", name="mouse") + >>> action_builder = ActionBuilder(driver) + >>> action_builder.add_pointer_input(kind="mouse", name="mouse") """ new_input = PointerInput(kind, name) self._add_input(new_input) @@ -131,19 +116,15 @@ def add_pointer_input(self, kind: str, name: str) -> PointerInput: def add_wheel_input(self, name: str) -> WheelInput: """Add a new wheel input device to the action builder. - Parameters: - ----------- - name : str - The name of the wheel input device. + Args: + name: The name of the wheel input device. Returns: - -------- - WheelInput : The newly created wheel input device. + The newly created wheel input device. Example: - -------- - >>> action_builder = ActionBuilder(driver) - >>> action_builder.add_wheel_input(name="wheel2") + >>> action_builder = ActionBuilder(driver) + >>> action_builder.add_wheel_input(name="wheel2") """ new_input = WheelInput(name) self._add_input(new_input) @@ -153,11 +134,10 @@ def perform(self) -> None: """Performs all stored actions. Example: - -------- - >>> action_builder = ActionBuilder(driver) - >>> keyboard = action_builder.key_input - >>> el = driver.find_element(id: "some_id") - >>> action_builder.click(el).pause(keyboard).pause(keyboard).pause(keyboard).send_keys("keys").perform() + >>> action_builder = ActionBuilder(driver) + >>> keyboard = action_builder.key_input + >>> el = driver.find_element(id: "some_id") + >>> action_builder.click(el).pause(keyboard).pause(keyboard).pause(keyboard).send_keys("keys").perform() """ enc: dict[str, list[Any]] = {"actions": []} for device in self.devices: @@ -171,21 +151,18 @@ def clear_actions(self) -> None: """Clears actions that are already stored on the remote end. Example: - -------- - >>> action_builder = ActionBuilder(driver) - >>> keyboard = action_builder.key_input - >>> el = driver.find_element(By.ID, "some_id") - >>> action_builder.click(el).pause(keyboard).pause(keyboard).pause(keyboard).send_keys("keys") - >>> action_builder.clear_actions() + >>> action_builder = ActionBuilder(driver) + >>> keyboard = action_builder.key_input + >>> el = driver.find_element(By.ID, "some_id") + >>> action_builder.click(el).pause(keyboard).pause(keyboard).pause(keyboard).send_keys("keys") + >>> action_builder.clear_actions() """ self.driver.execute(Command.W3C_CLEAR_ACTIONS) def _add_input(self, new_input: Union[KeyInput, PointerInput, WheelInput]) -> None: """Add a new input device to the action builder. - Parameters: - ----------- - new_input : Union[KeyInput, PointerInput, WheelInput] - The new input device to add. + Args: + new_input: The new input device to add. """ self.devices.append(new_input) diff --git a/py/selenium/webdriver/common/bidi/browser.py b/py/selenium/webdriver/common/bidi/browser.py index 73884ec08f0b7..cd42d6094ea28 100644 --- a/py/selenium/webdriver/common/bidi/browser.py +++ b/py/selenium/webdriver/common/bidi/browser.py @@ -59,7 +59,6 @@ def get_state(self) -> str: """Gets the state of the client window. Returns: - ------- str: The state of the client window (one of the ClientWindowState constants). """ return self.state @@ -68,7 +67,6 @@ def get_client_window(self) -> str: """Gets the client window identifier. Returns: - ------- str: The client window identifier. """ return self.client_window @@ -77,7 +75,6 @@ def get_width(self) -> int: """Gets the width of the client window. Returns: - ------- int: The width of the client window. """ return self.width @@ -86,7 +83,6 @@ def get_height(self) -> int: """Gets the height of the client window. Returns: - ------- int: The height of the client window. """ return self.height @@ -95,7 +91,6 @@ def get_x(self) -> int: """Gets the x coordinate of the client window. Returns: - ------- int: The x coordinate of the client window. """ return self.x @@ -104,7 +99,6 @@ def get_y(self) -> int: """Gets the y coordinate of the client window. Returns: - ------- int: The y coordinate of the client window. """ return self.y @@ -113,7 +107,6 @@ def is_active(self) -> bool: """Checks if the client window is active. Returns: - ------- bool: True if the client window is active, False otherwise. """ return self.active @@ -122,16 +115,13 @@ def is_active(self) -> bool: def from_dict(cls, data: dict) -> "ClientWindowInfo": """Creates a ClientWindowInfo instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the client window information. Returns: - ------- ClientWindowInfo: A new instance of ClientWindowInfo. Raises: - ------ ValueError: If required fields are missing or have invalid types. """ try: @@ -175,7 +165,7 @@ def from_dict(cls, data: dict) -> "ClientWindowInfo": active=active, ) except (KeyError, TypeError) as e: - raise ValueError(f"Invalid data format for ClientWindowInfo: {e}") + raise ValueError(f"Invalid data format for ClientWindowInfo: {e}") from e class Browser: @@ -194,14 +184,12 @@ def create_user_context( ) -> str: """Creates a new user context. - Parameters: - ----------- - accept_insecure_certs: Optional flag to accept insecure TLS certificates - proxy: Optional proxy configuration for the user context - unhandled_prompt_behavior: Optional configuration for handling user prompts + Args: + accept_insecure_certs: Optional flag to accept insecure TLS certificates. + proxy: Optional proxy configuration for the user context. + unhandled_prompt_behavior: Optional configuration for handling user prompts. Returns: - ------- str: The ID of the created user context. """ params: dict[str, Any] = {} @@ -222,7 +210,6 @@ def get_user_contexts(self) -> list[str]: """Gets all user contexts. Returns: - ------- List[str]: A list of user context IDs. """ result = self.conn.execute(command_builder("browser.getUserContexts", {})) @@ -231,16 +218,14 @@ def get_user_contexts(self) -> list[str]: def remove_user_context(self, user_context_id: str) -> None: """Removes a user context. - Parameters: - ----------- + Args: user_context_id: The ID of the user context to remove. Raises: - ------ - Exception: If the user context ID is "default" or does not exist. + ValueError: If the user context ID is "default" or does not exist. """ if user_context_id == "default": - raise Exception("Cannot remove the default user context") + raise ValueError("Cannot remove the default user context") params = {"userContext": user_context_id} self.conn.execute(command_builder("browser.removeUserContext", params)) @@ -249,7 +234,6 @@ def get_client_windows(self) -> list[ClientWindowInfo]: """Gets all client windows. Returns: - ------- List[ClientWindowInfo]: A list of client window information. """ result = self.conn.execute(command_builder("browser.getClientWindows", {})) diff --git a/py/selenium/webdriver/common/bidi/browsing_context.py b/py/selenium/webdriver/common/bidi/browsing_context.py index 3c2bdbf9ce2c5..a522528c7a6a2 100644 --- a/py/selenium/webdriver/common/bidi/browsing_context.py +++ b/py/selenium/webdriver/common/bidi/browsing_context.py @@ -59,13 +59,11 @@ def __init__( def from_json(cls, json: dict) -> "NavigationInfo": """Creates a NavigationInfo instance from a dictionary. - Parameters: - ----------- + Args: json: A dictionary containing the navigation information. Returns: - ------- - NavigationInfo: A new instance of NavigationInfo. + A new instance of NavigationInfo. """ context = json.get("context") if context is None or not isinstance(context, str): @@ -111,13 +109,11 @@ def __init__( def from_json(cls, json: dict) -> "BrowsingContextInfo": """Creates a BrowsingContextInfo instance from a dictionary. - Parameters: - ----------- + Args: json: A dictionary containing the browsing context information. Returns: - ------- - BrowsingContextInfo: A new instance of BrowsingContextInfo. + A new instance of BrowsingContextInfo. """ children = None raw_children = json.get("children") @@ -218,13 +214,11 @@ def __init__( def from_json(cls, json: dict) -> "UserPromptOpenedParams": """Creates a UserPromptOpenedParams instance from a dictionary. - Parameters: - ----------- + Args: json: A dictionary containing the user prompt parameters. Returns: - ------- - UserPromptOpenedParams: A new instance of UserPromptOpenedParams. + A new instance of UserPromptOpenedParams. """ context = json.get("context") if context is None or not isinstance(context, str): @@ -274,13 +268,11 @@ def __init__( def from_json(cls, json: dict) -> "UserPromptClosedParams": """Creates a UserPromptClosedParams instance from a dictionary. - Parameters: - ----------- + Args: json: A dictionary containing the user prompt closed parameters. Returns: - ------- - UserPromptClosedParams: A new instance of UserPromptClosedParams. + A new instance of UserPromptClosedParams. """ context = json.get("context") if context is None or not isinstance(context, str): @@ -323,13 +315,11 @@ def __init__( def from_json(cls, json: dict) -> "HistoryUpdatedParams": """Creates a HistoryUpdatedParams instance from a dictionary. - Parameters: - ----------- + Args: json: A dictionary containing the history updated parameters. Returns: - ------- - HistoryUpdatedParams: A new instance of HistoryUpdatedParams. + A new instance of HistoryUpdatedParams. """ context = json.get("context") if context is None or not isinstance(context, str): @@ -621,8 +611,7 @@ def validate_event(self, event: str) -> EventConfig: def subscribe_to_event(self, bidi_event: str, contexts: Optional[list[str]] = None) -> None: """Subscribe to a BiDi event if not already subscribed. - Parameters: - ---------- + Args: bidi_event: The BiDi event name. contexts: Optional browsing context IDs to subscribe to. """ @@ -635,8 +624,7 @@ def subscribe_to_event(self, bidi_event: str, contexts: Optional[list[str]] = No def unsubscribe_from_event(self, bidi_event: str) -> None: """Unsubscribe from a BiDi event if no more callbacks exist. - Parameters: - ---------- + Args: bidi_event: The BiDi event name. """ with self._subscription_lock: @@ -734,20 +722,17 @@ def get_event_names(cls) -> list[str]: """Get a list of all available event names. Returns: - ------- - List[str]: A list of event names that can be used with event handlers. + A list of event names that can be used with event handlers. """ return list(cls.EVENT_CONFIGS.keys()) def activate(self, context: str) -> None: """Activates and focuses the given top-level traversable. - Parameters: - ----------- + Args: context: The browsing context ID to activate. Raises: - ------ Exception: If the browsing context is not a top-level traversable. """ params = {"context": context} @@ -762,16 +747,14 @@ def capture_screenshot( ) -> str: """Captures an image of the given navigable, and returns it as a Base64-encoded string. - Parameters: - ----------- + Args: context: The browsing context ID to capture. origin: The origin of the screenshot, either "viewport" or "document". format: The format of the screenshot. clip: The clip rectangle of the screenshot. Returns: - ------- - str: The Base64-encoded screenshot. + The Base64-encoded screenshot. """ params: dict[str, Any] = {"context": context, "origin": origin} if format is not None: @@ -785,13 +768,11 @@ def capture_screenshot( def close(self, context: str, prompt_unload: bool = False) -> None: """Closes a top-level traversable. - Parameters: - ----------- + Args: context: The browsing context ID to close. prompt_unload: Whether to prompt to unload. Raises: - ------ Exception: If the browsing context is not a top-level traversable. """ params = {"context": context, "promptUnload": prompt_unload} @@ -806,16 +787,14 @@ def create( ) -> str: """Creates a new navigable, either in a new tab or in a new window, and returns its navigable id. - Parameters: - ----------- + Args: type: The type of the new navigable, either "tab" or "window". reference_context: The reference browsing context ID. background: Whether to create the new navigable in the background. user_context: The user context ID. Returns: - ------- - str: The browsing context ID of the created navigable. + The browsing context ID of the created navigable. """ params: dict[str, Any] = {"type": type} if reference_context is not None: @@ -836,14 +815,12 @@ def get_tree( """Returns a tree of all descendent navigables including the given parent itself, or all top-level contexts when no parent is provided. - Parameters: - ----------- + Args: max_depth: The maximum depth of the tree. root: The root browsing context ID. Returns: - ------- - List[BrowsingContextInfo]: A list of browsing context information. + A list of browsing context information. """ params: dict[str, Any] = {} if max_depth is not None: @@ -862,8 +839,7 @@ def handle_user_prompt( ) -> None: """Allows closing an open prompt. - Parameters: - ----------- + Args: context: The browsing context ID. accept: Whether to accept the prompt. user_text: The text to enter in the prompt. @@ -886,8 +862,7 @@ def locate_nodes( ) -> list[dict]: """Returns a list of all nodes matching the specified locator. - Parameters: - ----------- + Args: context: The browsing context ID. locator: The locator to use. max_node_count: The maximum number of nodes to return. @@ -895,8 +870,7 @@ def locate_nodes( start_nodes: The start nodes. Returns: - ------- - List[Dict]: A list of nodes. + A list of nodes. """ params: dict[str, Any] = {"context": context, "locator": locator} if max_node_count is not None: @@ -917,15 +891,13 @@ def navigate( ) -> dict: """Navigates a navigable to the given URL. - Parameters: - ----------- + Args: context: The browsing context ID. url: The URL to navigate to. wait: The readiness state to wait for. Returns: - ------- - Dict: A dictionary containing the navigation result. + A dictionary containing the navigation result. """ params = {"context": context, "url": url} if wait is not None: @@ -948,8 +920,7 @@ def print( """Creates a paginated representation of a document, and returns it as a PDF document represented as a Base64-encoded string. - Parameters: - ----------- + Args: context: The browsing context ID. background: Whether to include the background. margin: The margin parameters. @@ -960,8 +931,7 @@ def print( shrink_to_fit: Whether to shrink to fit. Returns: - ------- - str: The Base64-encoded PDF document. + The Base64-encoded PDF document. """ params = { "context": context, @@ -988,15 +958,13 @@ def reload( ) -> dict: """Reloads a navigable. - Parameters: - ----------- + Args: context: The browsing context ID. ignore_cache: Whether to ignore the cache. wait: The readiness state to wait for. Returns: - ------- - Dict: A dictionary containing the navigation result. + A dictionary containing the navigation result. """ params: dict[str, Any] = {"context": context} if ignore_cache is not None: @@ -1016,15 +984,13 @@ def set_viewport( ) -> None: """Modifies specific viewport characteristics on the given top-level traversable. - Parameters: - ----------- + Args: context: The browsing context ID. viewport: The viewport parameters. device_pixel_ratio: The device pixel ratio. user_contexts: The user context IDs. Raises: - ------ Exception: If the browsing context is not a top-level traversable. """ params: dict[str, Any] = {} @@ -1042,14 +1008,12 @@ def set_viewport( def traverse_history(self, context: str, delta: int) -> dict: """Traverses the history of a given navigable by a delta. - Parameters: - ----------- + Args: context: The browsing context ID. delta: The delta to traverse by. Returns: - ------- - Dict: A dictionary containing the traverse history result. + A dictionary containing the traverse history result. """ params = {"context": context, "delta": delta} result = self.conn.execute(command_builder("browsingContext.traverseHistory", params)) @@ -1058,23 +1022,20 @@ def traverse_history(self, context: str, delta: int) -> dict: def add_event_handler(self, event: str, callback: Callable, contexts: Optional[list[str]] = None) -> int: """Add an event handler to the browsing context. - Parameters: - ---------- + Args: event: The event to subscribe to. callback: The callback function to execute on event. contexts: The browsing context IDs to subscribe to. Returns: - ------- - int: callback id + Callback id. """ return self._event_manager.add_event_handler(event, callback, contexts) def remove_event_handler(self, event: str, callback_id: int) -> None: """Remove an event handler from the browsing context. - Parameters: - ---------- + Args: event: The event to unsubscribe from. callback_id: The callback id to remove. """ diff --git a/py/selenium/webdriver/common/bidi/common.py b/py/selenium/webdriver/common/bidi/common.py index 0aa87228e6ad3..be982cceafa99 100644 --- a/py/selenium/webdriver/common/bidi/common.py +++ b/py/selenium/webdriver/common/bidi/common.py @@ -22,13 +22,11 @@ def command_builder(method: str, params: Optional[dict] = None) -> Generator[dict, dict, dict]: """Build a command iterator to send to the BiDi protocol. - Parameters: - ----------- + Args: method: The method to execute. params: The parameters to pass to the method. Default is None. Returns: - -------- The response from the command execution. """ if params is None: diff --git a/py/selenium/webdriver/common/bidi/emulation.py b/py/selenium/webdriver/common/bidi/emulation.py index 85cd48422229b..8466e95aefb62 100644 --- a/py/selenium/webdriver/common/bidi/emulation.py +++ b/py/selenium/webdriver/common/bidi/emulation.py @@ -35,8 +35,7 @@ def __init__( ): """Initialize GeolocationCoordinates. - Parameters: - ----------- + Args: latitude: Latitude coordinate (-90.0 to 90.0). longitude: Longitude coordinate (-180.0 to 180.0). accuracy: Accuracy in meters (>= 0.0), defaults to 1.0. @@ -46,8 +45,8 @@ def __init__( speed: Speed in meters per second (>= 0.0) or None, defaults to None. Raises: - ------ - ValueError: If coordinates are out of valid range or if altitude_accuracy is provided without altitude. + ValueError: If coordinates are out of valid range or if altitude_accuracy + is provided without altitude. """ self.latitude = latitude self.longitude = longitude @@ -180,18 +179,16 @@ def set_geolocation_override( ) -> None: """Set geolocation override for the given contexts or user contexts. - Parameters: - ----------- + Args: coordinates: Geolocation coordinates to emulate, or None. error: Geolocation error to emulate, or None. contexts: List of browsing context IDs to apply the override to. user_contexts: List of user context IDs to apply the override to. Raises: - ------ ValueError: If both coordinates and error are provided, or if both contexts - and user_contexts are provided, or if neither contexts nor - user_contexts are provided. + and user_contexts are provided, or if neither contexts nor + user_contexts are provided. """ if coordinates is not None and error is not None: raise ValueError("Cannot specify both coordinates and error") @@ -224,17 +221,15 @@ def set_timezone_override( ) -> None: """Set timezone override for the given contexts or user contexts. - Parameters: - ----------- + Args: timezone: Timezone identifier (IANA timezone name or offset string like '+01:00'), - or None to clear the override. + or None to clear the override. contexts: List of browsing context IDs to apply the override to. user_contexts: List of user context IDs to apply the override to. Raises: - ------ ValueError: If both contexts and user_contexts are provided, or if neither - contexts nor user_contexts are provided. + contexts nor user_contexts are provided. """ if contexts is not None and user_contexts is not None: raise ValueError("Cannot specify both contexts and user_contexts") diff --git a/py/selenium/webdriver/common/bidi/input.py b/py/selenium/webdriver/common/bidi/input.py index 8b2f40e532210..452f418d8da37 100644 --- a/py/selenium/webdriver/common/bidi/input.py +++ b/py/selenium/webdriver/common/bidi/input.py @@ -356,12 +356,10 @@ class FileDialogInfo: def from_dict(cls, data: dict) -> "FileDialogInfo": """Creates a FileDialogInfo instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the file dialog information. Returns: - ------- FileDialogInfo: A new instance of FileDialogInfo. """ return cls(context=data["context"], multiple=data["multiple"], element=data.get("element")) @@ -396,8 +394,7 @@ def perform_actions( ) -> None: """Performs a sequence of user input actions. - Parameters: - ----------- + Args: context: The browsing context ID where actions should be performed. actions: A list of source actions to perform. """ @@ -407,8 +404,7 @@ def perform_actions( def release_actions(self, context: str) -> None: """Releases all input state for the given context. - Parameters: - ----------- + Args: context: The browsing context ID to release actions for. """ params = {"context": context} @@ -417,8 +413,7 @@ def release_actions(self, context: str) -> None: def set_files(self, context: str, element: dict, files: list[str]) -> None: """Sets files for a file input element. - Parameters: - ----------- + Args: context: The browsing context ID. element: The element reference (script.SharedReference). files: A list of file paths to set. @@ -426,15 +421,13 @@ def set_files(self, context: str, element: dict, files: list[str]) -> None: params = {"context": context, "element": element, "files": files} self.conn.execute(command_builder("input.setFiles", params)) - def add_file_dialog_handler(self, handler): + def add_file_dialog_handler(self, handler) -> int: """Add a handler for file dialog opened events. - Parameters: - ----------- + Args: handler: Callback function that takes a FileDialogInfo object. Returns: - -------- int: Callback ID for removing the handler later. """ # Subscribe to the event if not already subscribed @@ -454,8 +447,7 @@ def add_file_dialog_handler(self, handler): def remove_file_dialog_handler(self, callback_id: int) -> None: """Remove a file dialog handler. - Parameters: - ----------- + Args: callback_id: The callback ID returned by add_file_dialog_handler. """ if callback_id in self.callbacks: diff --git a/py/selenium/webdriver/common/bidi/network.py b/py/selenium/webdriver/common/bidi/network.py index 88ebdbb148241..9dfe802bbe14a 100644 --- a/py/selenium/webdriver/common/bidi/network.py +++ b/py/selenium/webdriver/common/bidi/network.py @@ -53,22 +53,19 @@ def __init__(self, conn): self.callbacks = {} self.subscriptions = {} - def _add_intercept(self, phases=[], contexts=None, url_patterns=None): + def _add_intercept(self, phases=None, contexts=None, url_patterns=None): """Add an intercept to the network. - Parameters: - ---------- - phases (list, optional): A list of phases to intercept. - Default is empty list. - contexts (list, optional): A list of contexts to intercept. - Default is None. - url_patterns (list, optional): A list of URL patterns to intercept. - Default is None. + Args: + phases: A list of phases to intercept. Default is None (empty list). + contexts: A list of contexts to intercept. Default is None. + url_patterns: A list of URL patterns to intercept. Default is None. Returns: - ------- - str : intercept id + str: intercept id """ + if phases is None: + phases = [] params = {} if contexts is not None: params["contexts"] = contexts @@ -87,17 +84,13 @@ def _add_intercept(self, phases=[], contexts=None, url_patterns=None): def _remove_intercept(self, intercept=None): """Remove a specific intercept, or all intercepts. - Parameters: - ---------- - intercept (str, optional): The intercept to remove. - Default is None. + Args: + intercept: The intercept to remove. Default is None. Raises: - ------ - Exception: If intercept is not found. + ValueError: If intercept is not found. - Notes: - ----- + Note: If intercept is None, all intercepts will be removed. """ if intercept is None: @@ -115,15 +108,13 @@ def _remove_intercept(self, intercept=None): def _on_request(self, event_name, callback): """Set a callback function to subscribe to a network event. - Parameters: - ---------- - event_name (str): The event to subscribe to. - callback (function): The callback function to execute on event. + Args: + event_name: The event to subscribe to. + callback: The callback function to execute on event. Takes Request object as argument. Returns: - ------- - int : callback id + int: callback id """ event = NetworkEvent(event_name) @@ -154,19 +145,15 @@ def _callback(event_data): def add_request_handler(self, event, callback, url_patterns=None, contexts=None): """Add a request handler to the network. - Parameters: - ---------- - event (str): The event to subscribe to. - url_patterns (list, optional): A list of URL patterns to intercept. - Default is None. - contexts (list, optional): A list of contexts to intercept. - Default is None. - callback (function): The callback function to execute on request interception + Args: + event: The event to subscribe to. + callback: The callback function to execute on request interception. Takes Request object as argument. + url_patterns: A list of URL patterns to intercept. Default is None. + contexts: A list of contexts to intercept. Default is None. Returns: - ------- - int : callback id + int: callback id """ try: @@ -192,10 +179,9 @@ def add_request_handler(self, event, callback, url_patterns=None, contexts=None) def remove_request_handler(self, event, callback_id): """Remove a request handler from the network. - Parameters: - ---------- - event_name (str): The event to unsubscribe from. - callback_id (int): The callback id to remove. + Args: + event: The event to unsubscribe from. + callback_id: The callback id to remove. """ try: event_name = self.EVENTS[event] @@ -231,14 +217,12 @@ def clear_request_handlers(self): def add_auth_handler(self, username, password): """Add an authentication handler to the network. - Parameters: - ---------- - username (str): The username to authenticate with. - password (str): The password to authenticate with. + Args: + username: The username to authenticate with. + password: The password to authenticate with. Returns: - ------- - int : callback id + int: callback id """ event = "auth_required" @@ -250,9 +234,8 @@ def _callback(request): def remove_auth_handler(self, callback_id): """Remove an authentication handler from the network. - Parameters: - ---------- - callback_id (int): The callback id to remove. + Args: + callback_id: The callback id to remove. """ event = "auth_required" self.remove_request_handler(event, callback_id) @@ -317,15 +300,12 @@ def continue_request(self, body=None, method=None, headers=None, cookies=None, u def _continue_with_auth(self, username=None, password=None): """Continue with authentication. - Parameters: - ---------- - request (Request): The request to continue with. - username (str): The username to authenticate with. - password (str): The password to authenticate with. + Args: + username: The username to authenticate with. + password: The password to authenticate with. - Notes: - ----- - If username or password is None, it attempts auth with no credentials + Note: + If username or password is None, it attempts auth with no credentials. """ params = {} diff --git a/py/selenium/webdriver/common/bidi/permissions.py b/py/selenium/webdriver/common/bidi/permissions.py index bb897f78dd6c7..84f6749d84813 100644 --- a/py/selenium/webdriver/common/bidi/permissions.py +++ b/py/selenium/webdriver/common/bidi/permissions.py @@ -55,16 +55,14 @@ def set_permission( ) -> None: """Sets a permission state for a given permission descriptor. - Parameters: - ----------- + Args: descriptor: The permission name (str) or PermissionDescriptor object. - Examples: "geolocation", "camera", "microphone" + Examples: "geolocation", "camera", "microphone". state: The permission state (granted, denied, prompt). origin: The origin for which the permission is set. user_context: The user context id (optional). Raises: - ------ ValueError: If the permission state is invalid. """ if state not in [PermissionState.GRANTED, PermissionState.DENIED, PermissionState.PROMPT]: diff --git a/py/selenium/webdriver/common/bidi/session.py b/py/selenium/webdriver/common/bidi/session.py index 32eab4fd74a9e..534cf861c2423 100644 --- a/py/selenium/webdriver/common/bidi/session.py +++ b/py/selenium/webdriver/common/bidi/session.py @@ -44,18 +44,16 @@ def __init__( ): """Initialize UserPromptHandler. - Parameters: - ----------- - alert: Handler type for alert prompts - before_unload: Handler type for beforeUnload prompts - confirm: Handler type for confirm prompts - default: Default handler type for all prompts - file: Handler type for file picker prompts - prompt: Handler type for prompt dialogs + Args: + alert: Handler type for alert prompts. + before_unload: Handler type for beforeUnload prompts. + confirm: Handler type for confirm prompts. + default: Default handler type for all prompts. + file: Handler type for file picker prompts. + prompt: Handler type for prompt dialogs. Raises: - ------ - ValueError: If any handler type is not valid + ValueError: If any handler type is not valid. """ for field_name, value in [ ("alert", alert), @@ -81,8 +79,7 @@ def to_dict(self) -> dict[str, str]: """Convert the UserPromptHandler to a dictionary for BiDi protocol. Returns: - ------- - Dict[str, str]: Dictionary representation suitable for BiDi protocol + Dictionary representation suitable for BiDi protocol. """ field_mapping = { "alert": "alert", @@ -126,14 +123,13 @@ def unsubscribe(self, *events, browsing_contexts=None): return command_builder("session.unsubscribe", params) def status(self): - """ - The session.status command returns information about the remote end's readiness - to create new sessions and may include implementation-specific metadata. + """The session.status command returns information about the remote end's readiness. + + Returns information about the remote end's readiness to create new sessions + and may include implementation-specific metadata. - Returns - ------- - dict - Dictionary containing the ready state (bool), message (str) and metadata + Returns: + Dictionary containing the ready state (bool), message (str) and metadata. """ cmd = command_builder("session.status", {}) return self.conn.execute(cmd) diff --git a/py/selenium/webdriver/common/bidi/storage.py b/py/selenium/webdriver/common/bidi/storage.py index 22d0c7d1aef7f..6e0ca289a313a 100644 --- a/py/selenium/webdriver/common/bidi/storage.py +++ b/py/selenium/webdriver/common/bidi/storage.py @@ -43,8 +43,7 @@ def to_dict(self) -> dict: """Converts the BytesValue to a dictionary. Returns: - ------- - Dict: A dictionary representation of the BytesValue. + A dictionary representation of the BytesValue. """ return {"type": self.type, "value": self.value} @@ -78,13 +77,11 @@ def __init__( def from_dict(cls, data: dict) -> "Cookie": """Creates a Cookie instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the cookie information. Returns: - ------- - Cookie: A new instance of Cookie. + A new instance of Cookie. """ # Validation for empty strings name = data.get("name") @@ -137,8 +134,7 @@ def to_dict(self) -> dict[str, Any]: """Converts the CookieFilter to a dictionary. Returns: - ------- - Dict: A dictionary representation of the CookieFilter. + A dictionary representation of the CookieFilter. """ result: dict[str, Any] = {} if self.name is not None: @@ -173,13 +169,11 @@ def __init__(self, user_context: Optional[str] = None, source_origin: Optional[s def from_dict(cls, data: dict) -> "PartitionKey": """Creates a PartitionKey instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the partition key information. Returns: - ------- - PartitionKey: A new instance of PartitionKey. + A new instance of PartitionKey. """ return cls( user_context=data.get("userContext"), @@ -198,7 +192,6 @@ def to_dict(self) -> dict: """Converts the BrowsingContextPartitionDescriptor to a dictionary. Returns: - ------- Dict: A dictionary representation of the BrowsingContextPartitionDescriptor. """ return {"type": self.type, "context": self.context} @@ -216,7 +209,6 @@ def to_dict(self) -> dict: """Converts the StorageKeyPartitionDescriptor to a dictionary. Returns: - ------- Dict: A dictionary representation of the StorageKeyPartitionDescriptor. """ result = {"type": self.type} @@ -286,13 +278,11 @@ def __init__(self, cookies: list[Cookie], partition_key: PartitionKey): def from_dict(cls, data: dict) -> "GetCookiesResult": """Creates a GetCookiesResult instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the get cookies result information. Returns: - ------- - GetCookiesResult: A new instance of GetCookiesResult. + A new instance of GetCookiesResult. """ cookies = [Cookie.from_dict(cookie) for cookie in data.get("cookies", [])] partition_key = PartitionKey.from_dict(data.get("partitionKey", {})) @@ -309,13 +299,11 @@ def __init__(self, partition_key: PartitionKey): def from_dict(cls, data: dict) -> "SetCookieResult": """Creates a SetCookieResult instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the set cookie result information. Returns: - ------- - SetCookieResult: A new instance of SetCookieResult. + A new instance of SetCookieResult. """ partition_key = PartitionKey.from_dict(data.get("partitionKey", {})) return cls(partition_key=partition_key) @@ -331,13 +319,11 @@ def __init__(self, partition_key: PartitionKey): def from_dict(cls, data: dict) -> "DeleteCookiesResult": """Creates a DeleteCookiesResult instance from a dictionary. - Parameters: - ----------- + Args: data: A dictionary containing the delete cookies result information. Returns: - ------- - DeleteCookiesResult: A new instance of DeleteCookiesResult. + A new instance of DeleteCookiesResult. """ partition_key = PartitionKey.from_dict(data.get("partitionKey", {})) return cls(partition_key=partition_key) @@ -354,16 +340,20 @@ def get_cookies( filter: Optional[CookieFilter] = None, partition: Optional[Union[BrowsingContextPartitionDescriptor, StorageKeyPartitionDescriptor]] = None, ) -> GetCookiesResult: - """Retrieves cookies that match the given parameters. + """Gets cookies matching the specified filter. - Parameters: - ----------- - filter: Optional filter to match cookies. - partition: Optional partition descriptor. + Args: + filter: Optional filter to specify which cookies to retrieve. + partition: Optional partition key to limit the scope of the operation. Returns: - ------- - GetCookiesResult: The result of the get cookies command. + A GetCookiesResult containing the cookies and partition key. + + Example: + result = await storage.get_cookies( + filter=CookieFilter(name="sessionId"), + partition=PartitionKey(...) + ) """ params = {} if filter is not None: @@ -381,14 +371,12 @@ def set_cookie( ) -> SetCookieResult: """Sets a cookie in the browser. - Parameters: - ----------- + Args: cookie: The cookie to set. partition: Optional partition descriptor. Returns: - ------- - SetCookieResult: The result of the set cookie command. + The result of the set cookie command. """ params = {"cookie": cookie.to_dict()} if partition is not None: @@ -404,14 +392,12 @@ def delete_cookies( ) -> DeleteCookiesResult: """Deletes cookies that match the given parameters. - Parameters: - ----------- + Args: filter: Optional filter to match cookies to delete. partition: Optional partition descriptor. Returns: - ------- - DeleteCookiesResult: The result of the delete cookies command. + The result of the delete cookies command. """ params = {} if filter is not None: diff --git a/py/selenium/webdriver/common/bidi/webextension.py b/py/selenium/webdriver/common/bidi/webextension.py index d91a89cfce2c2..3f6fa6c82e042 100644 --- a/py/selenium/webdriver/common/bidi/webextension.py +++ b/py/selenium/webdriver/common/bidi/webextension.py @@ -34,15 +34,13 @@ def install(self, path=None, archive_path=None, base64_value=None) -> dict: You must provide exactly one of the parameters. - Parameters: - ----------- - path: Path to an extension directory - archive_path: Path to an extension archive file - base64_value: Base64 encoded string of the extension archive + Args: + path: Path to an extension directory. + archive_path: Path to an extension archive file. + base64_value: Base64 encoded string of the extension archive. Returns: - ------- - Dict: A dictionary containing the extension ID. + A dictionary containing the extension ID. """ if sum(x is not None for x in (path, archive_path, base64_value)) != 1: raise ValueError("Exactly one of path, archive_path, or base64_value must be provided") @@ -70,10 +68,9 @@ def install(self, path=None, archive_path=None, base64_value=None) -> dict: def uninstall(self, extension_id_or_result: Union[str, dict]) -> None: """Uninstalls a web extension from the remote end. - Parameters: - ----------- + Args: extension_id_or_result: Either the extension ID as a string or the result dictionary - from a previous install() call containing the extension ID. + from a previous install() call containing the extension ID. """ if isinstance(extension_id_or_result, dict): extension_id = extension_id_or_result.get("extension") diff --git a/py/selenium/webdriver/common/options.py b/py/selenium/webdriver/common/options.py index 98247c3047222..5a8a9935c8308 100644 --- a/py/selenium/webdriver/common/options.py +++ b/py/selenium/webdriver/common/options.py @@ -163,266 +163,168 @@ class BaseOptions(metaclass=ABCMeta): """Gets and Sets the version of the browser. Usage: - ------ - - Get - - `self.browser_version` - - Set - - `self.browser_version` = `value` + - Get: `self.browser_version` + - Set: `self.browser_version = value` - Parameters: - ----------- - `value`: `str` + Args: + value: str Returns: - -------- - - Get - - `str` - - Set - - `None` + str when getting, None when setting. """ platform_name = _BaseOptionsDescriptor("platformName") """Gets and Sets name of the platform. Usage: - ------ - - Get - - `self.platform_name` - - Set - - `self.platform_name` = `value` + - Get: `self.platform_name` + - Set: `self.platform_name = value` - Parameters: - ----------- - `value`: `str` + Args: + value: str Returns: - -------- - - Get - - `str` - - Set - - `None` + str when getting, None when setting. """ accept_insecure_certs = _BaseOptionsDescriptor("acceptInsecureCerts") """Gets and Set whether the session accepts insecure certificates. Usage: - ------ - - Get - - `self.accept_insecure_certs` - - Set - - `self.accept_insecure_certs` = `value` + - Get: `self.accept_insecure_certs` + - Set: `self.accept_insecure_certs = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool Returns: - -------- - - Get - - `bool` - - Set - - `None` + bool when getting, None when setting. """ strict_file_interactability = _BaseOptionsDescriptor("strictFileInteractability") """Gets and Sets whether session is about file interactability. Usage: - ------ - - Get - - `self.strict_file_interactability` - - Set - - `self.strict_file_interactability` = `value` + - Get: `self.strict_file_interactability` + - Set: `self.strict_file_interactability = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool Returns: - -------- - - Get - - `bool` - - Set - - `None` + bool when getting, None when setting. """ set_window_rect = _BaseOptionsDescriptor("setWindowRect") """Gets and Sets window size and position. Usage: - ------ - - Get - - `self.set_window_rect` - - Set - - `self.set_window_rect` = `value` + - Get: `self.set_window_rect` + - Set: `self.set_window_rect = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool Returns: - -------- - - Get - - `bool` - - Set - - `None` + bool when getting, None when setting. """ enable_bidi = _BaseOptionsDescriptor("enableBidi") """Gets and Set whether the session has WebDriverBiDi enabled. Usage: - ------ - - Get - - `self.enable_bidi` - - Set - - `self.enable_bidi` = `value` + - Get: `self.enable_bidi` + - Set: `self.enable_bidi = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool Returns: - -------- - - Get - - `bool` - - Set - - `None` + bool when getting, None when setting. """ page_load_strategy = _PageLoadStrategyDescriptor("pageLoadStrategy") - """:Gets and Sets page load strategy, the default is "normal". + """Gets and Sets page load strategy, the default is "normal". Usage: - ------ - - Get - - `self.page_load_strategy` - - Set - - `self.page_load_strategy` = `value` + - Get: `self.page_load_strategy` + - Set: `self.page_load_strategy = value` - Parameters: - ----------- - `value`: `str` + Args: + value: str Returns: - -------- - - Get - - `str` - - Set - - `None` + str when getting, None when setting. """ unhandled_prompt_behavior = _UnHandledPromptBehaviorDescriptor("unhandledPromptBehavior") - """:Gets and Sets unhandled prompt behavior, the default is "dismiss and - notify". + """Gets and Sets unhandled prompt behavior, the default is "dismiss and notify". Usage: - ------ - - Get - - `self.unhandled_prompt_behavior` - - Set - - `self.unhandled_prompt_behavior` = `value` + - Get: `self.unhandled_prompt_behavior` + - Set: `self.unhandled_prompt_behavior = value` - Parameters: - ----------- - `value`: `str` + Args: + value: str Returns: - -------- - - Get - - `str` - - Set - - `None` + str when getting, None when setting. """ timeouts = _TimeoutsDescriptor("timeouts") - """:Gets and Sets implicit timeout, pageLoad timeout and script timeout if - set (in milliseconds) + """Gets and Sets implicit timeout, pageLoad timeout and script timeout if set (in milliseconds). Usage: - ------ - - Get - - `self.timeouts` - - Set - - `self.timeouts` = `value` + - Get: `self.timeouts` + - Set: `self.timeouts = value` - Parameters: - ----------- - `value`: `dict` + Args: + value: dict Returns: - -------- - - Get - - `dict` - - Set - - `None` + dict when getting, None when setting. """ proxy = _ProxyDescriptor("proxy") """Sets and Gets Proxy. Usage: - ------ - - Get - - `self.proxy` - - Set - - `self.proxy` = `value` + - Get: `self.proxy` + - Set: `self.proxy = value` - Parameters: - ----------- - `value`: `Proxy` + Args: + value: Proxy Returns: - -------- - - Get - - `Proxy` - - Set - - `None` + Proxy when getting, None when setting. """ enable_downloads = _BaseOptionsDescriptor("se:downloadsEnabled") """Gets and Sets whether session can download files. Usage: - ------ - - Get - - `self.enable_downloads` - - Set - - `self.enable_downloads` = `value` + - Get: `self.enable_downloads` + - Set: `self.enable_downloads = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool Returns: - -------- - - Get - - `bool` - - Set - - `None` + bool when getting, None when setting. """ web_socket_url = _BaseOptionsDescriptor("webSocketUrl") """Gets and Sets WebSocket URL. Usage: - ------ - - Get - - `self.web_socket_url` - - Set - - `self.web_socket_url` = `value` + - Get: `self.web_socket_url` + - Set: `self.web_socket_url = value` - Parameters: - ----------- - `value`: `str` + Args: + value: str Returns: - -------- - - Get - - `bool` - - Set - - `None` + str when getting, None when setting. """ def __init__(self) -> None: diff --git a/py/selenium/webdriver/common/print_page_options.py b/py/selenium/webdriver/common/print_page_options.py index 8207583714d7b..51167cc448039 100644 --- a/py/selenium/webdriver/common/print_page_options.py +++ b/py/selenium/webdriver/common/print_page_options.py @@ -159,243 +159,166 @@ class PrintOptions: page_height = _PageSettingsDescriptor("height") """Gets and Sets page_height: - Usage - ----- - - Get - - `self.page_height` - - Set - - `self.page_height` = `value` + Usage: + - Get: `self.page_height` + - Set: `self.page_height = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for page height. Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ page_width = _PageSettingsDescriptor("width") """Gets and Sets page_width: Usage: - ------ - - Get - - `self.page_width` - - Set - - `self.page_width` = `value` + - Get: `self.page_width` + - Set: `self.page_width = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for page width. Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ margin_top = _MarginSettingsDescriptor("top") """Gets and Sets margin_top: Usage: - ------ - - Get - - `self.margin_top` - - Set - - `self.margin_top` = `value` + - Get: `self.margin_top` + - Set: `self.margin_top = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for top margin. Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ margin_bottom = _MarginSettingsDescriptor("bottom") """Gets and Sets margin_bottom: Usage: - ------ - - Get - - `self.margin_bottom` - - Set - - `self.margin_bottom` = `value` + - Get: `self.margin_bottom` + - Set: `self.margin_bottom = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for bottom margin. Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ margin_left = _MarginSettingsDescriptor("left") """Gets and Sets margin_left: Usage: - ------ - - Get - - `self.margin_left` - - Set - - `self.margin_left` = `value` + - Get: `self.margin_left` + - Set: `self.margin_left = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for left margin. Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ margin_right = _MarginSettingsDescriptor("right") """Gets and Sets margin_right: Usage: - ------ - - Get - - `self.margin_right` - - Set - - `self.margin_right` = `value` + - Get: `self.margin_right` + - Set: `self.margin_right = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for right margin. Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ scale = _ScaleDescriptor("scale") """Gets and Sets scale: Usage: - ------ - - Get - - `self.scale` - - Set - - `self.scale` = `value` + - Get: `self.scale` + - Set: `self.scale = value` - Parameters: - ----------- - `value`: `float` + Args: + value: float value for scale (between 0.1 and 2). Returns: - -------- - - Get - - `Optional[float]` - - Set - - `None` + - Get: Optional[float] + - Set: None """ orientation = _PageOrientationDescriptor("orientation") """Gets and Sets orientation: Usage: - ------ - - Get - - `self.orientation` - - Set - - `self.orientation` = `value` + - Get: `self.orientation` + - Set: `self.orientation = value` - Parameters: - ----------- - `value`: `Orientation` + Args: + value: Orientation value ("portrait" or "landscape"). Returns: - -------- - - Get - - `Optional[Orientation]` - - Set - - `None` + - Get: Optional[Orientation] + - Set: None """ background = _ValidateBackGround("background") """Gets and Sets background: Usage: - ------ - - Get - - `self.background` - - Set - - `self.background` = `value` + - Get: `self.background` + - Set: `self.background = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool value for background printing. Returns: - -------- - - Get - - `Optional[bool]` - - Set - - `None` + - Get: Optional[bool] + - Set: None """ shrink_to_fit = _ValidateShrinkToFit("shrinkToFit") """Gets and Sets shrink_to_fit: Usage: - ------ - - Get - - `self.shrink_to_fit` - - Set - - `self.shrink_to_fit` = `value` + - Get: `self.shrink_to_fit` + - Set: `self.shrink_to_fit = value` - Parameters: - ----------- - `value`: `bool` + Args: + value: bool value for shrink to fit. Returns: - -------- - - Get - - `Optional[bool]` - - Set - - `None` + - Get: Optional[bool] + - Set: None """ page_ranges = _ValidatePageRanges("pageRanges") """Gets and Sets page_ranges: Usage: - ------ - - Get - - `self.page_ranges` - - Set - - `self.page_ranges` = `value` + - Get: `self.page_ranges` + - Set: `self.page_ranges = value` - Parameters: - ----------- - `value`: ` List[str]` + Args: + value: list of page range strings. Returns: - -------- - - Get - - `Optional[List[str]]` - - Set - - `None` + - Get: Optional[List[str]] + - Set: None """ # Reference for predefined page size constants: https://www.agooddaytoprint.com/page/paper-size-chart-faq A4 = {"height": 29.7, "width": 21.0} # size in cm @@ -418,15 +341,13 @@ def to_dict(self) -> _PrintOpts: def set_page_size(self, page_size: dict) -> None: """Sets the page size to predefined or custom dimensions. - Parameters: - ----------- - page_size: dict - A dictionary containing `height` and `width` as keys with respective values. + Args: + page_size: A dictionary containing 'height' and 'width' keys with + respective values in cm. Example: - -------- - self.set_page_size(PageSize.A4) # A4 predefined size - self.set_page_size({"height": 15.0, "width": 20.0}) # Custom size in cm + self.set_page_size(PageSize.A4) # A4 predefined size + self.set_page_size({"height": 15.0, "width": 20.0}) # Custom size """ self._validate_num_property("height", page_size["height"]) self._validate_num_property("width", page_size["width"]) diff --git a/py/selenium/webdriver/ie/options.py b/py/selenium/webdriver/ie/options.py index 82cba38f57657..a38a64d49ea76 100644 --- a/py/selenium/webdriver/ie/options.py +++ b/py/selenium/webdriver/ie/options.py @@ -109,258 +109,190 @@ class Options(ArgOptions): # Creating descriptor objects for each of the above IE options browser_attach_timeout = _IeOptionsDescriptor(BROWSER_ATTACH_TIMEOUT, int) - """Gets and Sets `browser_attach_timeout` + """Gets and Sets `browser_attach_timeout`. Usage: - ------ - - Get - - `self.browser_attach_timeout` - - Set - - `self.browser_attach_timeout` = `value` - - Parameters: - ----------- - `value`: `int` (Timeout) in milliseconds + - Get: `self.browser_attach_timeout` + - Set: `self.browser_attach_timeout = value` + + Args: + value: int - Timeout in milliseconds. """ element_scroll_behavior = _IeOptionsDescriptor(ELEMENT_SCROLL_BEHAVIOR, Enum) - """Gets and Sets `element_scroll_behavior` + """Gets and Sets `element_scroll_behavior`. Usage: - ------ - - Get - - `self.element_scroll_behavior` - - Set - - `self.element_scroll_behavior` = `value` - - Parameters: - ----------- - `value`: `int` either 0 - Top, 1 - Bottom + - Get: `self.element_scroll_behavior` + - Set: `self.element_scroll_behavior = value` + + Args: + value: int - Either 0 (Top) or 1 (Bottom). """ ensure_clean_session = _IeOptionsDescriptor(ENSURE_CLEAN_SESSION, bool) - """Gets and Sets `ensure_clean_session` + """Gets and Sets `ensure_clean_session`. Usage: - ------ - - Get - - `self.ensure_clean_session` - - Set - - `self.ensure_clean_session` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.ensure_clean_session` + - Set: `self.ensure_clean_session = value` + + Args: + value: bool """ file_upload_dialog_timeout = _IeOptionsDescriptor(FILE_UPLOAD_DIALOG_TIMEOUT, int) - """Gets and Sets `file_upload_dialog_timeout` + """Gets and Sets `file_upload_dialog_timeout`. Usage: - ------ - - Get - - `self.file_upload_dialog_timeout` - - Set - - `self.file_upload_dialog_timeout` = `value` - - Parameters: - ----------- - `value`: `int` (Timeout) in milliseconds + - Get: `self.file_upload_dialog_timeout` + - Set: `self.file_upload_dialog_timeout = value` + + Args: + value: int - Timeout in milliseconds. """ force_create_process_api = _IeOptionsDescriptor(FORCE_CREATE_PROCESS_API, bool) - """Gets and Sets `force_create_process_api` + """Gets and Sets `force_create_process_api`. Usage: - ------ - - Get - - `self.force_create_process_api` - - Set - - `self.force_create_process_api` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.force_create_process_api` + - Set: `self.force_create_process_api = value` + + Args: + value: bool """ force_shell_windows_api = _IeOptionsDescriptor(FORCE_SHELL_WINDOWS_API, bool) - """Gets and Sets `force_shell_windows_api` + """Gets and Sets `force_shell_windows_api`. Usage: - ------ - - Get - - `self.force_shell_windows_api` - - Set - - `self.force_shell_windows_api` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.force_shell_windows_api` + - Set: `self.force_shell_windows_api = value` + + Args: + value: bool """ full_page_screenshot = _IeOptionsDescriptor(FULL_PAGE_SCREENSHOT, bool) - """Gets and Sets `full_page_screenshot` + """Gets and Sets `full_page_screenshot`. Usage: - ------ - - Get - - `self.full_page_screenshot` - - Set - - `self.full_page_screenshot` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.full_page_screenshot` + - Set: `self.full_page_screenshot = value` + + Args: + value: bool """ ignore_protected_mode_settings = _IeOptionsDescriptor(IGNORE_PROTECTED_MODE_SETTINGS, bool) - """Gets and Sets `ignore_protected_mode_settings` + """Gets and Sets `ignore_protected_mode_settings`. Usage: - ------ - - Get - - `self.ignore_protected_mode_settings` - - Set - - `self.ignore_protected_mode_settings` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.ignore_protected_mode_settings` + - Set: `self.ignore_protected_mode_settings = value` + + Args: + value: bool """ ignore_zoom_level = _IeOptionsDescriptor(IGNORE_ZOOM_LEVEL, bool) - """Gets and Sets `ignore_zoom_level` + """Gets and Sets `ignore_zoom_level`. Usage: - ------ - - Get - - `self.ignore_zoom_level` - - Set - - `self.ignore_zoom_level` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.ignore_zoom_level` + - Set: `self.ignore_zoom_level = value` + + Args: + value: bool """ initial_browser_url = _IeOptionsDescriptor(INITIAL_BROWSER_URL, str) - """Gets and Sets `initial_browser_url` + """Gets and Sets `initial_browser_url`. Usage: - ------ - - Get - - `self.initial_browser_url` - - Set - - `self.initial_browser_url` = `value` - - Parameters: - ----------- - `value`: `str` + - Get: `self.initial_browser_url` + - Set: `self.initial_browser_url = value` + + Args: + value: str """ native_events = _IeOptionsDescriptor(NATIVE_EVENTS, bool) - """Gets and Sets `native_events` + """Gets and Sets `native_events`. Usage: - ------ - - Get - - `self.native_events` - - Set - - `self.native_events` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.native_events` + - Set: `self.native_events = value` + + Args: + value: bool """ persistent_hover = _IeOptionsDescriptor(PERSISTENT_HOVER, bool) - """Gets and Sets `persistent_hover` + """Gets and Sets `persistent_hover`. Usage: - ------ - - Get - - `self.persistent_hover` - - Set - - `self.persistent_hover` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.persistent_hover` + - Set: `self.persistent_hover = value` + + Args: + value: bool """ require_window_focus = _IeOptionsDescriptor(REQUIRE_WINDOW_FOCUS, bool) - """Gets and Sets `require_window_focus` + """Gets and Sets `require_window_focus`. Usage: - ------ - - Get - - `self.require_window_focus` - - Set - - `self.require_window_focus` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.require_window_focus` + - Set: `self.require_window_focus = value` + + Args: + value: bool """ use_per_process_proxy = _IeOptionsDescriptor(USE_PER_PROCESS_PROXY, bool) - """Gets and Sets `use_per_process_proxy` + """Gets and Sets `use_per_process_proxy`. Usage: - ------ - - Get - - `self.use_per_process_proxy` - - Set - - `self.use_per_process_proxy` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.use_per_process_proxy` + - Set: `self.use_per_process_proxy = value` + + Args: + value: bool """ use_legacy_file_upload_dialog_handling = _IeOptionsDescriptor(USE_LEGACY_FILE_UPLOAD_DIALOG_HANDLING, bool) - """Gets and Sets `use_legacy_file_upload_dialog_handling` + """Gets and Sets `use_legacy_file_upload_dialog_handling`. Usage: - ------ - - Get - - `self.use_legacy_file_upload_dialog_handling` - - Set - - `self.use_legacy_file_upload_dialog_handling` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.use_legacy_file_upload_dialog_handling` + - Set: `self.use_legacy_file_upload_dialog_handling = value` + + Args: + value: bool """ attach_to_edge_chrome = _IeOptionsDescriptor(ATTACH_TO_EDGE_CHROME, bool) - """Gets and Sets `attach_to_edge_chrome` + """Gets and Sets `attach_to_edge_chrome`. Usage: - ------ - - Get - - `self.attach_to_edge_chrome` - - Set - - `self.attach_to_edge_chrome` = `value` - - Parameters: - ----------- - `value`: `bool` + - Get: `self.attach_to_edge_chrome` + - Set: `self.attach_to_edge_chrome = value` + + Args: + value: bool """ edge_executable_path = _IeOptionsDescriptor(EDGE_EXECUTABLE_PATH, str) - """Gets and Sets `edge_executable_path` + """Gets and Sets `edge_executable_path`. Usage: - ------ - - Get - - `self.edge_executable_path` - - Set - - `self.edge_executable_path` = `value` - - Parameters: - ----------- - `value`: `str` + - Get: `self.edge_executable_path` + - Set: `self.edge_executable_path = value` + + Args: + value: str """ def __init__(self) -> None: diff --git a/py/selenium/webdriver/remote/server.py b/py/selenium/webdriver/remote/server.py index 09e9e647331fe..1a6467f0ebf2e 100644 --- a/py/selenium/webdriver/remote/server.py +++ b/py/selenium/webdriver/remote/server.py @@ -35,21 +35,14 @@ class Server: For more information on Selenium Grid, see: - https://www.selenium.dev/documentation/grid/getting_started/ - Parameters: - ----------- - host : str - Hostname or IP address to bind to (determined automatically if not specified) - port : int or str - Port to listen on (4444 if not specified) - path : str - Path/filename of existing server .jar file (Selenium Manager is used if not specified) - version : str - Version of server to download (latest version if not specified) - log_level : str - Logging level to control logging output ("INFO" if not specified) - Available levels: "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST" - env: collections.abc.Mapping - Mapping that defines the environment variables for the server process + Args: + host: Hostname or IP address to bind to (determined automatically if not specified). + port: Port to listen on (4444 if not specified). + path: Path/filename of existing server .jar file (Selenium Manager is used if not specified). + version: Version of server to download (latest version if not specified). + log_level: Logging level to control logging output ("INFO" if not specified). + Available levels: "SEVERE", "WARNING", "INFO", "CONFIG", "FINE", "FINER", "FINEST". + env: Mapping that defines the environment variables for the server process. """ def __init__(self, host=None, port=4444, path=None, version=None, log_level="INFO", env=None): diff --git a/py/selenium/webdriver/remote/shadowroot.py b/py/selenium/webdriver/remote/shadowroot.py index f23f5c42e38c8..16e33796a4e95 100644 --- a/py/selenium/webdriver/remote/shadowroot.py +++ b/py/selenium/webdriver/remote/shadowroot.py @@ -48,28 +48,23 @@ def find_element(self, by: str = By.ID, value: str = None): """Find an element inside a shadow root given a By strategy and locator. - Parameters: - ----------- - by : selenium.webdriver.common.by.By - The locating strategy to use. Default is `By.ID`. Supported values include: - - By.ID: Locate by element ID. - - By.NAME: Locate by the `name` attribute. - - By.XPATH: Locate by an XPath expression. - - By.CSS_SELECTOR: Locate by a CSS selector. - - By.CLASS_NAME: Locate by the `class` attribute. - - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). - - By.LINK_TEXT: Locate a link element by its exact text. - - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. - - RelativeBy: Locate elements relative to a specified root element. - - Example: - -------- - element = driver.find_element(By.ID, 'foo') + Args: + by: The locating strategy to use. Default is `By.ID`. Supported values include: + - By.ID: Locate by element ID. + - By.NAME: Locate by the `name` attribute. + - By.XPATH: Locate by an XPath expression. + - By.CSS_SELECTOR: Locate by a CSS selector. + - By.CLASS_NAME: Locate by the `class` attribute. + - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). + - By.LINK_TEXT: Locate a link element by its exact text. + - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. + - RelativeBy: Locate elements relative to a specified root element. Returns: - ------- - WebElement The first matching `WebElement` found on the page. + + Example: + >>> element = driver.find_element(By.ID, "foo") """ if by == By.ID: by = By.CSS_SELECTOR @@ -85,31 +80,26 @@ def find_element(self, by: str = By.ID, value: str = None): return self._execute(Command.FIND_ELEMENT_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"] - def find_elements(self, by: str = By.ID, value: str = None): + def find_elements(self, by: str = By.ID, value: str = None) -> list: """Find elements inside a shadow root given a By strategy and locator. - Parameters: - ----------- - by : selenium.webdriver.common.by.By - The locating strategy to use. Default is `By.ID`. Supported values include: - - By.ID: Locate by element ID. - - By.NAME: Locate by the `name` attribute. - - By.XPATH: Locate by an XPath expression. - - By.CSS_SELECTOR: Locate by a CSS selector. - - By.CLASS_NAME: Locate by the `class` attribute. - - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). - - By.LINK_TEXT: Locate a link element by its exact text. - - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. - - RelativeBy: Locate elements relative to a specified root element. - - Example: - -------- - element = driver.find_elements(By.ID, 'foo') + Args: + by: The locating strategy to use. Default is `By.ID`. Supported values include: + - By.ID: Locate by element ID. + - By.NAME: Locate by the `name` attribute. + - By.XPATH: Locate by an XPath expression. + - By.CSS_SELECTOR: Locate by a CSS selector. + - By.CLASS_NAME: Locate by the `class` attribute. + - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). + - By.LINK_TEXT: Locate a link element by its exact text. + - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. + - RelativeBy: Locate elements relative to a specified root element. Returns: - ------- - List[WebElement] - list of `WebElements` matching locator strategy found on the page. + List of `WebElements` matching locator strategy found on the page. + + Example: + >>> element = driver.find_elements(By.ID, "foo") """ if by == By.ID: by = By.CSS_SELECTOR diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py index 143064f1a6697..c32a05b846009 100644 --- a/py/selenium/webdriver/remote/webdriver.py +++ b/py/selenium/webdriver/remote/webdriver.py @@ -93,10 +93,8 @@ def _create_caps(caps): Moves the Firefox profile, if present, from the old location to the new Firefox options object. - Parameters: - ----------- - caps : dict - - A dictionary of capabilities requested by the caller. + Args: + caps: A dictionary of capabilities requested by the caller. """ caps = copy.deepcopy(caps) always_match = {} @@ -209,24 +207,21 @@ def __init__( """Create a new driver that will issue commands using the wire protocol. - Parameters: - ----------- - command_executor : str or remote_connection.RemoteConnection - - 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 : bool (Deprecated) - - Whether to configure remote_connection.RemoteConnection to use HTTP keep-alive. Defaults to True. - file_detector : object or None - - Pass a custom file detector object during instantiation. If None, the default - LocalFileDetector() will be used. - options : options.Options - - Instance of a driver options.Options class. - locator_converter : object or None - - Custom locator converter to use. Defaults to None. - web_element_cls : class - - Custom class to use for web elements. Defaults to WebElement. - client_config : object or None - - Custom client configuration to use. Defaults to None. + 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. """ if options is None: @@ -295,21 +290,18 @@ def file_detector_context(self, file_detector_class, *args, **kwargs): """Overrides the current file detector (if necessary) in limited context. Ensures the original file detector is set afterwards. - Parameters: - ----------- - file_detector_class : object - - 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 : tuple - - Optional arguments that get passed to the file detector class during instantiation. - kwargs : dict - - Keyword arguments, passed the same way as args. + 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') + >>> with webdriver.file_detector_context(UselessFileDetector): + >>> someinput.send_keys('/etc/hosts') """ last_detector = None if not isinstance(self.file_detector, file_detector_class): @@ -330,8 +322,7 @@ def name(self) -> str: """Returns the name of the underlying browser for this instance. Example: - -------- - >>> name = driver.name + >>> name = driver.name """ if "browserName" in self.caps: return self.caps["browserName"] @@ -355,10 +346,8 @@ def stop_client(self): def start_session(self, capabilities: dict) -> None: """Creates a new session with the desired capabilities. - Parameters: - ----------- - capabilities : dict - - A capabilities dict to start the session with. + Args: + capabilities: A capabilities dict to start the session with. """ caps = _create_caps(capabilities) @@ -408,41 +397,29 @@ def execute_cdp_cmd(self, cmd: str, cmd_args: dict): domains/commands, refer to link https://chromedevtools.github.io/devtools-protocol/ - Parameters: - ----------- - cmd : str, - - Command name - - cmd_args : dict - - Command args - - Empty dict {} if there is no command args + 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'} + 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}) - + >>> driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": requestId}) """ return self.execute("executeCdpCommand", {"cmd": cmd, "params": cmd_args})["value"] def execute(self, driver_command: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]: """Sends a command to be executed by a command.CommandExecutor. - Parameters: - ----------- - driver_command : str - - The name of the command to execute as a string. - - params : dict - - A dictionary of named Parameters to send with the command. + 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: - -------- - dict - The command's JSON response loaded into a dictionary object. + The command's JSON response loaded into a dictionary object. """ params = self._wrap_value(params) @@ -469,16 +446,13 @@ def get(self, url: str) -> None: The method does not return until the page is fully loaded (i.e. the onload event has fired). - Parameters: - ----------- - url : str - - The URL to be opened by the browser. - - Must include the protocol (e.g., http://, https://). + Args: + url: The URL to be opened by the browser. Must include the protocol + (e.g., http://, https://). Example: - -------- - >>> driver = webdriver.Chrome() - >>> driver.get("https://example.com") + >>> driver = webdriver.Chrome() + >>> driver.get("https://example.com") """ self.execute(Command.GET, {"url": url}) @@ -487,9 +461,8 @@ def title(self) -> str: """Returns the title of the current page. Example: - -------- - >>> element = driver.find_element(By.ID, "foo") - >>> print(element.title()) + >>> element = driver.find_element(By.ID, "foo") + >>> print(element.title()) """ return self.execute(Command.GET_TITLE).get("value", "") @@ -498,8 +471,7 @@ def pin_script(self, script: str, script_key=None) -> ScriptKey: hashable ID. Example: - -------- - >>> script = "return document.getElementById('foo').value" + >>> script = "return document.getElementById('foo').value" """ script_key_instance = ScriptKey(script_key) self.pinned_scripts[script_key_instance.id] = script @@ -509,8 +481,7 @@ def unpin(self, script_key: ScriptKey) -> None: """Remove a pinned script from storage. Example: - -------- - >>> driver.unpin(script_key) + >>> driver.unpin(script_key) """ try: self.pinned_scripts.pop(script_key.id) @@ -521,27 +492,21 @@ def get_pinned_scripts(self) -> list[str]: """Return a list of all pinned scripts. Example: - -------- - >>> pinned_scripts = driver.get_pinned_scripts() + >>> pinned_scripts = driver.get_pinned_scripts() """ return list(self.pinned_scripts) def execute_script(self, script: str, *args): """Synchronously Executes JavaScript in the current window/frame. - Parameters: - ----------- - script : str - - The javascript to execute. - - *args : tuple - - Any applicable arguments for your JavaScript. + Args: + script: The javascript to execute. + *args: Any applicable arguments for your JavaScript. Example: - -------- - >>> input_id = "username" - >>> input_value = "test_user" - >>> driver.execute_script("document.getElementById(arguments[0]).value = arguments[1];", input_id, input_value) + >>> id = "username" + >>> value = "test_user" + >>> driver.execute_script("document.getElementById(arguments[0]).value = arguments[1];", id, value) """ if isinstance(script, ScriptKey): try: @@ -557,19 +522,14 @@ def execute_script(self, script: str, *args): def execute_async_script(self, script: str, *args): """Asynchronously Executes JavaScript in the current window/frame. - Parameters: - ----------- - script : str - - The javascript to execute. - - *args : tuple - - Any applicable arguments for your JavaScript. + 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) + >>> script = "var callback = arguments[arguments.length - 1]; " + ... "window.setTimeout(function(){ callback('timeout') }, 3000);" + >>> driver.execute_async_script(script) """ converted_args = list(args) command = Command.W3C_EXECUTE_SCRIPT_ASYNC @@ -581,8 +541,7 @@ def current_url(self) -> str: """Gets the URL of the current page. Example: - -------- - >>> print(driver.current_url) + >>> print(driver.current_url) """ return self.execute(Command.GET_CURRENT_URL)["value"] @@ -591,8 +550,7 @@ def page_source(self) -> str: """Gets the source of the current page. Example: - -------- - >>> print(driver.page_source) + >>> print(driver.page_source) """ return self.execute(Command.GET_PAGE_SOURCE)["value"] @@ -600,8 +558,7 @@ def close(self) -> None: """Closes the current window. Example: - -------- - >>> driver.close() + >>> driver.close() """ self.execute(Command.CLOSE) @@ -609,8 +566,7 @@ def quit(self) -> None: """Quits the driver and closes every associated window. Example: - -------- - >>> driver.quit() + >>> driver.quit() """ try: self.execute(Command.QUIT) @@ -624,8 +580,7 @@ def current_window_handle(self) -> str: """Returns the handle of the current window. Example: - -------- - >>> print(driver.current_window_handle) + >>> print(driver.current_window_handle) """ return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)["value"] @@ -634,8 +589,7 @@ def window_handles(self) -> list[str]: """Returns the handles of all windows within the current session. Example: - -------- - >>> print(driver.window_handles) + >>> print(driver.window_handles) """ return self.execute(Command.W3C_GET_WINDOW_HANDLES)["value"] @@ -643,8 +597,7 @@ def maximize_window(self) -> None: """Maximizes the current window that webdriver is using. Example: - -------- - >>> driver.maximize_window() + >>> driver.maximize_window() """ command = Command.W3C_MAXIMIZE_WINDOW self.execute(command, None) @@ -653,8 +606,7 @@ def fullscreen_window(self) -> None: """Invokes the window manager-specific 'full screen' operation. Example: - -------- - >>> driver.fullscreen_window() + >>> driver.fullscreen_window() """ self.execute(Command.FULLSCREEN_WINDOW) @@ -666,11 +618,10 @@ def print_page(self, print_options: Optional[PrintOptions] = None) -> str: """Takes PDF of the current page. The driver makes a best effort to return a PDF based on the - provided Parameters. + provided parameters. Example: - -------- - >>> driver.print_page() + >>> driver.print_page() """ options: Union[dict[str, Any], Any] = {} if print_options: @@ -683,19 +634,17 @@ def switch_to(self) -> SwitchTo: """Return an object containing all options to switch focus into. Returns: - -------- - SwitchTo: an object containing all options to switch focus into. + 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") + >>> 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") """ return self._switch_to @@ -704,8 +653,7 @@ def back(self) -> None: """Goes one step backward in the browser history. Example: - -------- - >>> driver.back() + >>> driver.back() """ self.execute(Command.GO_BACK) @@ -713,8 +661,7 @@ def forward(self) -> None: """Goes one step forward in the browser history. Example: - -------- - >>> driver.forward() + >>> driver.forward() """ self.execute(Command.GO_FORWARD) @@ -722,8 +669,7 @@ def refresh(self) -> None: """Refreshes the current page. Example: - -------- - >>> driver.refresh() + >>> driver.refresh() """ self.execute(Command.REFRESH) @@ -733,12 +679,11 @@ def get_cookies(self) -> list[dict]: the current session. Returns: - -------- - cookies:List[dict] : A list of dictionaries, corresponding to cookies visible in the current + A list of dictionaries, corresponding to cookies visible in the + current session. Example: - -------- - >>> cookies = driver.get_cookies() + >>> cookies = driver.get_cookies() """ return self.execute(Command.GET_ALL_COOKIES)["value"] @@ -747,8 +692,7 @@ def get_cookie(self, name) -> Optional[dict]: or whitespace. Returns the cookie if found, None if not. Example: - -------- - >>> cookie = driver.get_cookie("my_cookie") + >>> cookie = driver.get_cookie("my_cookie") """ if not name or name.isspace(): raise ValueError("Cookie name cannot be empty") @@ -763,8 +707,7 @@ def delete_cookie(self, name) -> None: the name is empty or whitespace. Example: - -------- - >>> driver.delete_cookie("my_cookie") + >>> driver.delete_cookie("my_cookie") """ # firefox deletes all cookies when "" is passed as name @@ -777,26 +720,23 @@ def delete_all_cookies(self) -> None: """Delete all cookies in the scope of the session. Example: - -------- - >>> driver.delete_all_cookies() + >>> driver.delete_all_cookies() """ self.execute(Command.DELETE_ALL_COOKIES) def add_cookie(self, cookie_dict) -> None: """Adds a cookie to your current session. - Parameters: - ----------- - cookie_dict : dict - - A dictionary object, with required keys - "name" and "value"; - - Optional keys - "path", "domain", "secure", "httpOnly", "expiry", "sameSite" + 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"}) + >>> 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"}) """ if "sameSite" in cookie_dict: assert cookie_dict["sameSite"] in ["Strict", "Lax", "None"] @@ -811,14 +751,11 @@ def implicitly_wait(self, time_to_wait: float) -> None: per session. To set the timeout for calls to execute_async_script, see set_script_timeout. - Parameters: - ----------- - time_to_wait : float - - Amount of time to wait (in seconds) + Args: + time_to_wait: Amount of time to wait (in seconds). Example: - -------- - >>> driver.implicitly_wait(30) + >>> driver.implicitly_wait(30) """ self.execute(Command.SET_TIMEOUTS, {"implicit": int(float(time_to_wait) * 1000)}) @@ -826,14 +763,11 @@ def set_script_timeout(self, time_to_wait: float) -> None: """Set the amount of time that the script should wait during an execute_async_script call before throwing an error. - Parameters: - ----------- - time_to_wait : float - - The amount of time to wait (in seconds) + Args: + time_to_wait: The amount of time to wait (in seconds). Example: - -------- - >>> driver.set_script_timeout(30) + >>> driver.set_script_timeout(30) """ self.execute(Command.SET_TIMEOUTS, {"script": int(float(time_to_wait) * 1000)}) @@ -841,14 +775,11 @@ def set_page_load_timeout(self, time_to_wait: float) -> None: """Set the amount of time 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) + Args: + time_to_wait: The amount of time to wait (in seconds). Example: - -------- - >>> driver.set_page_load_timeout(30) + >>> driver.set_page_load_timeout(30) """ try: self.execute(Command.SET_TIMEOUTS, {"pageLoad": int(float(time_to_wait) * 1000)}) @@ -860,15 +791,13 @@ def timeouts(self) -> Timeouts: """Get all the timeouts that have been set on the current session. Returns: - -------- - Timeouts: 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. + 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 + >>> driver.timeouts """ timeouts = self.execute(Command.GET_TIMEOUTS)["value"] timeouts["implicit_wait"] = timeouts.pop("implicit") / 1000 @@ -882,38 +811,26 @@ def timeouts(self, timeouts) -> None: set timeouts. Example: - -------- - >>> my_timeouts = Timeouts() - >>> my_timeouts.implicit_wait = 10 - >>> driver.timeouts = my_timeouts + >>> my_timeouts = Timeouts() + >>> my_timeouts.implicit_wait = 10 + >>> driver.timeouts = my_timeouts """ _ = self.execute(Command.SET_TIMEOUTS, timeouts._to_json())["value"] def find_element(self, by=By.ID, value: Optional[str] = None) -> WebElement: """Find an element given a By strategy and locator. - Parameters: - ----------- - by : selenium.webdriver.common.by.By - The locating strategy to use. Default is `By.ID`. Supported values include: - - By.ID: Locate by element ID. - - By.NAME: Locate by the `name` attribute. - - By.XPATH: Locate by an XPath expression. - - By.CSS_SELECTOR: Locate by a CSS selector. - - By.CLASS_NAME: Locate by the `class` attribute. - - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). - - By.LINK_TEXT: Locate a link element by its exact text. - - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. - - RelativeBy: Locate elements relative to a specified root element. - - Example: - -------- - element = driver.find_element(By.ID, 'foo') + 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. Returns: - ------- - WebElement - The first matching `WebElement` found on the page. + The first matching WebElement found on the page. + + Example: + element = driver.find_element(By.ID, 'foo') """ by, value = self.locator_converter.convert(by, value) @@ -928,28 +845,17 @@ def find_element(self, by=By.ID, value: Optional[str] = None) -> WebElement: def find_elements(self, by=By.ID, value: Optional[str] = None) -> list[WebElement]: """Find elements given a By strategy and locator. - Parameters: - ----------- - by : selenium.webdriver.common.by.By - The locating strategy to use. Default is `By.ID`. Supported values include: - - By.ID: Locate by element ID. - - By.NAME: Locate by the `name` attribute. - - By.XPATH: Locate by an XPath expression. - - By.CSS_SELECTOR: Locate by a CSS selector. - - By.CLASS_NAME: Locate by the `class` attribute. - - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). - - By.LINK_TEXT: Locate a link element by its exact text. - - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. - - RelativeBy: Locate elements relative to a specified root element. - - Example: - -------- - element = driver.find_elements(By.ID, 'foo') + 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. Returns: - ------- - List[WebElement] - list of `WebElements` matching locator strategy found on the page. + List of WebElements matching locator strategy found on the page. + + Example: + element = driver.find_elements(By.ID, 'foo') """ by, value = self.locator_converter.convert(by, value) @@ -971,8 +877,7 @@ def capabilities(self) -> dict: """Returns the drivers current capabilities being used. Example: - -------- - >>> print(driver.capabilities) + >>> print(driver.capabilities) """ return self.caps @@ -981,15 +886,12 @@ def get_screenshot_as_file(self, filename) -> bool: Returns False if there is any IOError, else returns True. Use full paths in your filename. - Parameters: - ----------- - filename : str - - The full path you wish to save your screenshot to. This - - should end with a `.png` extension. + 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") + >>> driver.get_screenshot_as_file("/Screenshots/foo.png") """ if not str(filename).lower().endswith(".png"): warnings.warn( @@ -1012,15 +914,12 @@ def save_screenshot(self, filename) -> bool: Returns False if there is any IOError, else returns True. Use full paths in your filename. - Parameters: - ----------- - filename : str - - The full path you wish to save your screenshot to. This - - should end with a `.png` extension. + 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") + >>> driver.save_screenshot("/Screenshots/foo.png") """ return self.get_screenshot_as_file(filename) @@ -1028,8 +927,7 @@ def get_screenshot_as_png(self) -> bytes: """Gets the screenshot of the current window as a binary data. Example: - -------- - >>> driver.get_screenshot_as_png() + >>> driver.get_screenshot_as_png() """ return b64decode(self.get_screenshot_as_base64().encode("ascii")) @@ -1038,25 +936,19 @@ def get_screenshot_as_base64(self) -> str: which is useful in embedded images in HTML. Example: - -------- - >>> driver.get_screenshot_as_base64() + >>> driver.get_screenshot_as_base64() """ return self.execute(Command.SCREENSHOT)["value"] def set_window_size(self, width, height, windowHandle: str = "current") -> None: """Sets the width and height of the current window. (window.resizeTo) - Parameters: - ----------- - width : int - - the width in pixels to set the window to - - height : int - - the height in pixels to set the window to + Args: + width: The width in pixels to set the window to. + height: The height in pixels to set the window to. Example: - -------- - >>> driver.set_window_size(800, 600) + >>> driver.set_window_size(800, 600) """ self._check_if_window_handle_is_current(windowHandle) self.set_window_rect(width=int(width), height=int(height)) @@ -1065,8 +957,7 @@ def get_window_size(self, windowHandle: str = "current") -> dict: """Gets the width and height of the current window. Example: - -------- - >>> driver.get_window_size() + >>> driver.get_window_size() """ self._check_if_window_handle_is_current(windowHandle) @@ -1080,17 +971,12 @@ def get_window_size(self, windowHandle: str = "current") -> dict: def set_window_position(self, x: float, y: float, windowHandle: str = "current") -> dict: """Sets the x,y position of the current window. (window.moveTo) - 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 + Args: + x: The x-coordinate in pixels to set the window position. + y: The y-coordinate in pixels to set the window position. Example: - -------- - >>> driver.set_window_position(0, 0) + >>> driver.set_window_position(0, 0) """ self._check_if_window_handle_is_current(windowHandle) return self.set_window_rect(x=int(x), y=int(y)) @@ -1099,8 +985,7 @@ def get_window_position(self, windowHandle="current") -> dict: """Gets the x,y position of the current window. Example: - -------- - >>> driver.get_window_position() + >>> driver.get_window_position() """ self._check_if_window_handle_is_current(windowHandle) @@ -1118,8 +1003,7 @@ def get_window_rect(self) -> dict: of the current window. Example: - -------- - >>> driver.get_window_rect() + >>> driver.get_window_rect() """ return self.execute(Command.GET_WINDOW_RECT)["value"] @@ -1130,10 +1014,9 @@ def set_window_rect(self, x=None, y=None, width=None, height=None) -> dict: `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) + >>> 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) """ if (x is None and y is None) and (not height and not width): @@ -1150,14 +1033,10 @@ def file_detector(self, detector) -> None: """Set the file detector to be used when sending keyboard input. By default, this is set to a file detector that does nothing. - - see FileDetector - - see LocalFileDetector - - see UselessFileDetector + See FileDetector, LocalFileDetector, and UselessFileDetector. - Parameters: - ----------- - detector : Any - - The detector to use. Must not be None. + Args: + detector: The detector to use. Must not be None. """ if not detector: raise WebDriverException("You may not set a file detector that is null") @@ -1170,8 +1049,7 @@ def orientation(self): """Gets the current orientation of the device. Example: - -------- - >>> orientation = driver.orientation + >>> orientation = driver.orientation """ return self.execute(Command.GET_SCREEN_ORIENTATION)["value"] @@ -1179,14 +1057,11 @@ def orientation(self): def orientation(self, value) -> None: """Sets the current orientation of the device. - Parameters: - ----------- - value : str - - orientation to set it to. + Args: + value: Orientation to set it to. Example: - -------- - >>> driver.orientation = "landscape" + >>> driver.orientation = "landscape" """ allowed_values = ["LANDSCAPE", "PORTRAIT"] if value.upper() in allowed_values: @@ -1285,15 +1160,13 @@ def browser(self): """Returns a browser module object for BiDi browser commands. Returns: - -------- - Browser: an object containing access to BiDi browser commands. + 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) + >>> 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) """ if not self._websocket_connection: self._start_bidi() @@ -1321,15 +1194,13 @@ def browsing_context(self): commands. Returns: - -------- - BrowsingContext: an object containing access to BiDi browsing context commands. + 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) + >>> 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) """ if not self._websocket_connection: self._start_bidi() @@ -1344,17 +1215,15 @@ def storage(self): """Returns a storage module object for BiDi storage commands. Returns: - -------- - Storage: an object containing access to BiDi storage commands. + An object containing access to BiDi storage commands. Examples: - --------- - >>> cookie_filter = CookieFilter(name="example") - >>> result = driver.storage.get_cookies(filter=cookie_filter) - >>> driver.storage.set_cookie(cookie=PartialCookie( - "name", BytesValue(BytesValue.TYPE_STRING, "value"), "domain") - ) - >>> driver.storage.delete_cookies(filter=CookieFilter(name="example")) + >>> cookie_filter = CookieFilter(name="example") + >>> result = driver.storage.get_cookies(filter=cookie_filter) + >>> driver.storage.set_cookie(cookie=PartialCookie( + "name", BytesValue(BytesValue.TYPE_STRING, "value"), "domain") + ) + >>> driver.storage.delete_cookies(filter=CookieFilter(name="example")) """ if not self._websocket_connection: self._start_bidi() @@ -1369,14 +1238,12 @@ def permissions(self): """Returns a permissions module object for BiDi permissions commands. Returns: - -------- - Permissions: an object containing access to BiDi permissions commands. + 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") + >>> from selenium.webdriver.common.bidi.permissions import PermissionDescriptor, PermissionState + >>> descriptor = PermissionDescriptor("geolocation") + >>> driver.permissions.set_permission(descriptor, PermissionState.GRANTED, "https://example.com") """ if not self._websocket_connection: self._start_bidi() @@ -1391,14 +1258,12 @@ def webextension(self): """Returns a webextension module object for BiDi webextension commands. Returns: - -------- - WebExtension: an object containing access to BiDi webextension commands. + 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) + >>> extension_path = "/path/to/extension" + >>> extension_result = driver.webextension.install(path=extension_path) + >>> driver.webextension.uninstall(extension_result) """ if not self._websocket_connection: self._start_bidi() @@ -1413,14 +1278,12 @@ def emulation(self): """Returns an emulation module object for BiDi emulation commands. Returns: - -------- - Emulation: an object containing access to BiDi emulation commands. + 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]) + >>> from selenium.webdriver.common.bidi.emulation import GeolocationCoordinates + >>> coordinates = GeolocationCoordinates(37.7749, -122.4194) + >>> driver.emulation.set_geolocation_override(coordinates=coordinates, contexts=[context_id]) """ if not self._websocket_connection: self._start_bidi() @@ -1435,15 +1298,13 @@ def input(self): """Returns an input module object for BiDi input commands. Returns: - -------- - Input: an object containing access to BiDi input commands. + An object containing access to BiDi input commands. Examples: - --------- - >>> from selenium.webdriver.common.bidi.input import KeySourceActions, KeyDownAction, KeyUpAction - >>> key_actions = KeySourceActions(id="keyboard", actions=[KeyDownAction(value="a"), KeyUpAction(value="a")]) - >>> driver.input.perform_actions(driver.current_window_handle, [key_actions]) - >>> driver.input.release_actions(driver.current_window_handle) + >>> 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) """ if not self._websocket_connection: self._start_bidi() @@ -1484,10 +1345,9 @@ def add_virtual_authenticator(self, options: VirtualAuthenticatorOptions) -> Non """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) + >>> from selenium.webdriver.common.virtual_authenticator import VirtualAuthenticatorOptions + >>> options = VirtualAuthenticatorOptions(protocol="u2f", transport="usb", device_id="myDevice123") + >>> driver.add_virtual_authenticator(options) """ self._authenticator_id = self.execute(Command.ADD_VIRTUAL_AUTHENTICATOR, options.to_dict())["value"] @@ -1496,8 +1356,7 @@ def virtual_authenticator_id(self) -> Optional[str]: """Returns the id of the virtual authenticator. Example: - -------- - >>> print(driver.virtual_authenticator_id) + >>> print(driver.virtual_authenticator_id) """ return self._authenticator_id @@ -1509,8 +1368,7 @@ def remove_virtual_authenticator(self) -> None: methods may be called. Example: - -------- - >>> driver.remove_virtual_authenticator() + >>> driver.remove_virtual_authenticator() """ self.execute(Command.REMOVE_VIRTUAL_AUTHENTICATOR, {"authenticatorId": self._authenticator_id}) self._authenticator_id = None @@ -1520,10 +1378,9 @@ def add_credential(self, credential: Credential) -> None: """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) + >>> from selenium.webdriver.common.credential import Credential + >>> credential = Credential(id="user@example.com", password="aPassword") + >>> driver.add_credential(credential) """ self.execute(Command.ADD_CREDENTIAL, {**credential.to_dict(), "authenticatorId": self._authenticator_id}) @@ -1532,8 +1389,7 @@ def get_credentials(self) -> list[Credential]: """Returns the list of credentials owned by the authenticator. Example: - -------- - >>> credentials = driver.get_credentials() + >>> credentials = driver.get_credentials() """ credential_data = self.execute(Command.GET_CREDENTIALS, {"authenticatorId": self._authenticator_id}) return [Credential.from_dict(credential) for credential in credential_data["value"]] @@ -1543,9 +1399,8 @@ def remove_credential(self, credential_id: Union[str, bytearray]) -> None: """Removes a credential from the authenticator. Example: - -------- - >>> credential_id = "user@example.com" - >>> driver.remove_credential(credential_id) + >>> credential_id = "user@example.com" + >>> driver.remove_credential(credential_id) """ # Check if the credential is bytearray converted to b64 string if isinstance(credential_id, bytearray): @@ -1560,8 +1415,7 @@ def remove_all_credentials(self) -> None: """Removes all credentials from the authenticator. Example: - -------- - >>> driver.remove_all_credentials() + >>> driver.remove_all_credentials() """ self.execute(Command.REMOVE_ALL_CREDENTIALS, {"authenticatorId": self._authenticator_id}) @@ -1570,13 +1424,12 @@ def set_user_verified(self, verified: bool) -> None: """Sets whether the authenticator will simulate success or fail on user verification. - Parameters: - ----------- - verified: True if the authenticator will pass user verification, False otherwise. + Args: + verified: True if the authenticator will pass user verification, + False otherwise. Example: - -------- - >>> driver.set_user_verified(True) + >>> driver.set_user_verified(True) """ self.execute(Command.SET_USER_VERIFIED, {"authenticatorId": self._authenticator_id, "isUserVerified": verified}) @@ -1584,8 +1437,7 @@ def get_downloadable_files(self) -> list: """Retrieves the downloadable files as a list of file names. Example: - -------- - >>> files = driver.get_downloadable_files() + >>> files = driver.get_downloadable_files() """ if "se:downloadsEnabled" not in self.capabilities: raise WebDriverException("You must enable downloads in order to work with downloadable files.") @@ -1596,17 +1448,13 @@ def download_file(self, file_name: str, target_directory: str) -> None: """Downloads a file with the specified file name to the target directory. - Parameters: - ----------- - file_name : str - - The name of the file to download. - - target_directory : str - - The path to the directory to save the downloaded file. + 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") + >>> driver.download_file("example.zip", "/path/to/directory") """ if "se:downloadsEnabled" not in self.capabilities: raise WebDriverException("You must enable downloads in order to work with downloadable files.") @@ -1628,8 +1476,7 @@ def delete_downloadable_files(self) -> None: """Deletes all downloadable files. Example: - -------- - >>> driver.delete_downloadable_files() + >>> driver.delete_downloadable_files() """ if "se:downloadsEnabled" not in self.capabilities: raise WebDriverException("You must enable downloads in order to work with downloadable files.") @@ -1642,21 +1489,20 @@ def fedcm(self) -> FedCM: for interaction. Returns: - ------- - FedCM: an object providing access to all Federated Credential Management (FedCM) dialog commands. + An object providing access to all Federated Credential Management + (FedCM) dialog commands. Examples: - -------- - >>> title = driver.fedcm.title - >>> subtitle = driver.fedcm.subtitle - >>> dialog_type = driver.fedcm.dialog_type - >>> accounts = 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() + >>> title = driver.fedcm.title + >>> subtitle = driver.fedcm.subtitle + >>> dialog_type = driver.fedcm.dialog_type + >>> accounts = 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() """ return self._fedcm @@ -1665,8 +1511,7 @@ def supports_fedcm(self) -> bool: """Returns whether the browser supports FedCM capabilities. Example: - -------- - >>> print(driver.supports_fedcm) + >>> print(driver.supports_fedcm) """ return self.capabilities.get(ArgOptions.FEDCM_CAPABILITY, False) @@ -1683,8 +1528,7 @@ def dialog(self): """Returns the FedCM dialog object for interaction. Example: - -------- - >>> dialog = driver.dialog + >>> dialog = driver.dialog """ self._require_fedcm_support() return Dialog(self) @@ -1692,25 +1536,17 @@ def dialog(self): def fedcm_dialog(self, timeout=5, poll_frequency=0.5, ignored_exceptions=None): """Waits for and returns the FedCM dialog. - Parameters: - ----------- - timeout : int - - How long to wait for the dialog - - poll_frequency : floatHow - - Frequently to poll - - ignored_exceptions : Any - - Exceptions to ignore while waiting + 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 + The FedCM dialog object if found. Raises: - ------- - TimeoutException if dialog doesn't appear - WebDriverException if FedCM not supported + TimeoutException: If dialog doesn't appear. + WebDriverException: If FedCM not supported. """ from selenium.common.exceptions import NoAlertPresentException from selenium.webdriver.support.wait import WebDriverWait diff --git a/py/selenium/webdriver/remote/webelement.py b/py/selenium/webdriver/remote/webelement.py index f9db08f05f76c..24ba178745974 100644 --- a/py/selenium/webdriver/remote/webelement.py +++ b/py/selenium/webdriver/remote/webelement.py @@ -84,12 +84,10 @@ def tag_name(self) -> str: """This element's ``tagName`` property. Returns: - -------- - str : The tag name of the element. + The tag name of the element. Example: - -------- - >>> element = driver.find_element(By.ID, "foo") + >>> element = driver.find_element(By.ID, "foo") """ return self._execute(Command.GET_ELEMENT_TAG_NAME)["value"] @@ -98,13 +96,11 @@ def text(self) -> str: """The text of the element. Returns: - -------- - str : The text of the element. + The text of the element. Example: - -------- - >>> element = driver.find_element(By.ID, "foo") - >>> print(element.text) + >>> element = driver.find_element(By.ID, "foo") + >>> print(element.text) """ return self._execute(Command.GET_ELEMENT_TEXT)["value"] @@ -112,9 +108,8 @@ def click(self) -> None: """Clicks the element. Example: - -------- - >>> element = driver.find_element(By.ID, "foo") - >>> element.click() + >>> element = driver.find_element(By.ID, "foo") + >>> element.click() """ self._execute(Command.CLICK_ELEMENT) @@ -122,9 +117,8 @@ def submit(self) -> None: """Submits a form. Example: - -------- - >>> form = driver.find_element(By.NAME, "login") - >>> form.submit() + >>> form = driver.find_element(By.NAME, "login") + >>> form.submit() """ script = ( "/* submitForm */var form = arguments[0];\n" @@ -147,27 +141,22 @@ def clear(self) -> None: """Clears the text if it's a text entry element. Example: - -------- - >>> text_field = driver.find_element(By.NAME, "username") - >>> text_field.clear() + >>> text_field = driver.find_element(By.NAME, "username") + >>> text_field.clear() """ self._execute(Command.CLEAR_ELEMENT) def get_property(self, name) -> str | bool | WebElement | dict: """Gets the given property of the element. - Parameters: - ----------- - name : str - - Name of the property to retrieve. + Args: + name: Name of the property to retrieve. Returns: - ------- - str | bool | WebElement | dict : The value of the property. + The value of the property. Example: - ------- - >>> text_length = target_element.get_property("text_length") + >>> text_length = target_element.get_property("text_length") """ try: return self._execute(Command.GET_ELEMENT_PROPERTY, {"name": name})["value"] @@ -180,18 +169,14 @@ def get_dom_attribute(self, name) -> str: :func:`~selenium.webdriver.remote.BaseWebElement.get_attribute`, this method only returns attributes declared in the element's HTML markup. - Parameters: - ----------- - name : str - - Name of the attribute to retrieve. + Args: + name: Name of the attribute to retrieve. Returns: - ------- - str : The value of the attribute. + The value of the attribute. Example: - ------- - >>> text_length = target_element.get_dom_attribute("class") + >>> text_length = target_element.get_dom_attribute("class") """ return self._execute(Command.GET_ELEMENT_ATTRIBUTE, {"name": name})["value"] @@ -212,19 +197,15 @@ def get_attribute(self, name) -> str | None: use :func:`~selenium.webdriver.remote.BaseWebElement.get_dom_attribute` or :func:`~selenium.webdriver.remote.BaseWebElement.get_property` methods respectively. - Parameters: - ----------- - name : str - - Name of the attribute/property to retrieve. + Args: + name: Name of the attribute/property to retrieve. Returns: - ------- - str | bool | None : The value of the attribute/property. + The value of the attribute/property. Example: - -------- - >>> # Check if the "active" CSS class is applied to an element. - >>> is_active = "active" in target_element.get_attribute("class") + >>> # Check if the "active" CSS class is applied to an element. + >>> is_active = "active" in target_element.get_attribute("class") """ if getAttribute_js is None: _load_js() @@ -236,14 +217,11 @@ def get_attribute(self, name) -> str | None: def is_selected(self) -> bool: """Returns whether the element is selected. - Example: - -------- - >>> is_selected = element.is_selected() + This method is generally used on checkboxes, options in a select + and radio buttons. - Notes: - ------ - - This method is generally used on checkboxes, options in a select - and radio buttons. + Example: + >>> is_selected = element.is_selected() """ return self._execute(Command.IS_ELEMENT_SELECTED)["value"] @@ -251,39 +229,35 @@ def is_enabled(self) -> bool: """Returns whether the element is enabled. Example: - -------- - >>> is_enabled = element.is_enabled() + >>> is_enabled = element.is_enabled() """ return self._execute(Command.IS_ELEMENT_ENABLED)["value"] def send_keys(self, *value: str) -> None: """Simulates typing into the element. - Parameters: - ----------- - value : str - - 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. + This can also be used to set file inputs. - Notes: - ------ - - Use this to send simple key events or to fill out form fields - - This can also be used to set file inputs. + Args: + value: A string for typing, or setting form fields. For setting + file inputs, this could be a local file path. Examples: - -------- - To send a simple key event:: - >>> form_textfield = driver.find_element(By.NAME, "username") - >>> form_textfield.send_keys("admin") - - or to set a file input field:: - >>> 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")) - >>> # When using Cygwin, the path need to be provided in Windows format. - >>> # file_input.send_keys(f"C:/cygwin{os.path.abspath('path/to/profilepic.gif').replace('/', '\\')}") + To send a simple key event:: + + >>> form_textfield = driver.find_element(By.NAME, "username") + >>> form_textfield.send_keys("admin") + + or to set a file input field:: + + >>> 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")) + >>> # When using Cygwin, the path need to be provided in Windows format. + >>> # file_input.send_keys(f"C:/cygwin{os.path.abspath('path/to/profilepic.gif').replace('/', '\\')}") """ # transfer file to another machine only if remote driver is used # the same behaviour as for java binding @@ -309,20 +283,19 @@ def shadow_root(self) -> ShadowRoot: """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. + If the alert is present it switches the given driver to it. + Returns: - ------- - ShadowRoot : object + The ShadowRoot object. Raises: - ------- - NoSuchShadowRoot - if no shadow root was attached to element + NoSuchShadowRoot: If no shadow root was attached to element. Example: - -------- - >>> try: - ... shadow_root = element.shadow_root - >>> except NoSuchShadowRoot: - ... print("No shadow root attached to element") + >>> try: + ... shadow_root = element.shadow_root + >>> except NoSuchShadowRoot: + ... print("No shadow root attached to element") """ return self._execute(Command.GET_SHADOW_ROOT)["value"] @@ -331,8 +304,7 @@ def is_displayed(self) -> bool: """Whether the element is visible to a user. Example: - -------- - >>> is_displayed = element.is_displayed() + >>> is_displayed = element.is_displayed() """ # Only go into this conditional for browsers that don't use the atom themselves if isDisplayed_js is None: @@ -346,13 +318,11 @@ def location_once_scrolled_into_view(self) -> dict: cause the element to be scrolled into view. Returns: - -------- - dict: the top lefthand corner location on the screen, or zero + The top lefthand corner location on the screen, or zero coordinates if the element is not visible. Example: - -------- - >>> loc = element.location_once_scrolled_into_view + >>> loc = element.location_once_scrolled_into_view """ old_loc = self._execute( Command.W3C_EXECUTE_SCRIPT, @@ -368,12 +338,10 @@ def size(self) -> dict: """The size of the element. Returns: - -------- - dict: The width and height of the element. + The width and height of the element. Example: - -------- - >>> size = element.size + >>> size = element.size """ size = self._execute(Command.GET_ELEMENT_RECT)["value"] new_size = {"height": size["height"], "width": size["width"]} @@ -382,18 +350,14 @@ def size(self) -> dict: def value_of_css_property(self, property_name) -> str: """The value of a CSS property. - Parameters: - ----------- - property_name : str - - The name of the CSS property to get the value of. + Args: + property_name: The name of the CSS property to get the value of. Returns: - -------- - str : The value of the CSS property. + The value of the CSS property. Example: - -------- - >>> value = element.value_of_css_property("color") + >>> value = element.value_of_css_property("color") """ return self._execute(Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, {"propertyName": property_name})["value"] @@ -402,12 +366,10 @@ def location(self) -> dict: """The location of the element in the renderable canvas. Returns: - -------- - dict: The x and y coordinates of the element. + The x and y coordinates of the element. Example: - -------- - >>> loc = element.location + >>> loc = element.location """ old_loc = self._execute(Command.GET_ELEMENT_RECT)["value"] new_loc = {"x": round(old_loc["x"]), "y": round(old_loc["y"])} @@ -418,12 +380,10 @@ def rect(self) -> dict: """A dictionary with the size and location of the element. Returns: - -------- - dict: The size and location of the element. + The size and location of the element. Example: - -------- - >>> rect = element.rect + >>> rect = element.rect """ return self._execute(Command.GET_ELEMENT_RECT)["value"] @@ -432,12 +392,10 @@ def aria_role(self) -> str: """Returns the ARIA role of the current web element. Returns: - -------- - str : The ARIA role of the element. + The ARIA role of the element. Example: - -------- - >>> role = element.aria_role + >>> role = element.aria_role """ return self._execute(Command.GET_ELEMENT_ARIA_ROLE)["value"] @@ -446,12 +404,10 @@ def accessible_name(self) -> str: """Returns the ARIA Level of the current webelement. Returns: - -------- - str : The ARIA Level of the element. + The ARIA Level of the element. Example: - -------- - >>> name = element.accessible_name + >>> name = element.accessible_name """ return self._execute(Command.GET_ELEMENT_ARIA_LABEL)["value"] @@ -461,12 +417,10 @@ def screenshot_as_base64(self) -> str: string. Returns: - -------- - str : The screenshot of the element as a base64 encoded string. + The screenshot of the element as a base64 encoded string. Example: - -------- - >>> img_b64 = element.screenshot_as_base64 + >>> img_b64 = element.screenshot_as_base64 """ return self._execute(Command.ELEMENT_SCREENSHOT)["value"] @@ -475,12 +429,10 @@ def screenshot_as_png(self) -> bytes: """Gets the screenshot of the current element as a binary data. Returns: - -------- - bytes : The screenshot of the element as binary data. + The screenshot of the element as binary data. Example: - -------- - >>> element_png = element.screenshot_as_png + >>> element_png = element.screenshot_as_png """ return b64decode(self.screenshot_as_base64.encode("ascii")) @@ -489,19 +441,15 @@ def screenshot(self, filename) -> bool: 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. + Returns: - -------- - bool : True if the screenshot was saved successfully, False otherwise. - - Parameters: - ----------- - filename : str - The full path you wish to save your screenshot to. This - should end with a `.png` extension. - - Element: - -------- - >>> element.screenshot("/Screenshots/foo.png") + True if the screenshot was saved successfully, False otherwise. + + Example: + >>> element.screenshot("/Screenshots/foo.png") """ if not filename.lower().endswith(".png"): warnings.warn( @@ -524,9 +472,8 @@ def parent(self): from. Example: - -------- - >>> element = driver.find_element(By.ID, "foo") - >>> parent_element = element.parent + >>> element = driver.find_element(By.ID, "foo") + >>> parent_element = element.parent """ return self._parent @@ -538,9 +485,8 @@ def id(self) -> str: webelements refer to the same element, can be done using ``==``:: Example: - -------- - >>> if element1 == element2: - ... print("These 2 are equal") + >>> if element1 == element2: + ... print("These 2 are equal") """ return self._id @@ -554,17 +500,12 @@ def __ne__(self, element): def _execute(self, command, params=None): """Executes a command against the underlying HTML element. - Parameters: - ----------- - command : any - The name of the command to _execute as a string. - - params : dict - A dictionary of named Parameters to send with the command. + Args: + 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. + The command's JSON response loaded into a dictionary object. """ if not params: params = {} @@ -574,28 +515,23 @@ def _execute(self, command, params=None): def find_element(self, by=By.ID, value=None) -> WebElement: """Find an element given a By strategy and locator. - Parameters: - ----------- - by : selenium.webdriver.common.by.By - The locating strategy to use. Default is `By.ID`. Supported values include: - - By.ID: Locate by element ID. - - By.NAME: Locate by the `name` attribute. - - By.XPATH: Locate by an XPath expression. - - By.CSS_SELECTOR: Locate by a CSS selector. - - By.CLASS_NAME: Locate by the `class` attribute. - - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). - - By.LINK_TEXT: Locate a link element by its exact text. - - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. - - RelativeBy: Locate elements relative to a specified root element. - - Example: - -------- - element = driver.find_element(By.ID, 'foo') + Args: + by: The locating strategy to use. Default is `By.ID`. Supported values include: + - By.ID: Locate by element ID. + - By.NAME: Locate by the `name` attribute. + - By.XPATH: Locate by an XPath expression. + - By.CSS_SELECTOR: Locate by a CSS selector. + - By.CLASS_NAME: Locate by the `class` attribute. + - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). + - By.LINK_TEXT: Locate a link element by its exact text. + - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. + - RelativeBy: Locate elements relative to a specified root element. Returns: - ------- - WebElement The first matching `WebElement` found on the page. + + Example: + >>> element = driver.find_element(By.ID, "foo") """ by, value = self._parent.locator_converter.convert(by, value) return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})["value"] @@ -603,28 +539,23 @@ def find_element(self, by=By.ID, value=None) -> WebElement: def find_elements(self, by=By.ID, value=None) -> list[WebElement]: """Find elements given a By strategy and locator. - Parameters: - ----------- - by : selenium.webdriver.common.by.By - The locating strategy to use. Default is `By.ID`. Supported values include: - - By.ID: Locate by element ID. - - By.NAME: Locate by the `name` attribute. - - By.XPATH: Locate by an XPath expression. - - By.CSS_SELECTOR: Locate by a CSS selector. - - By.CLASS_NAME: Locate by the `class` attribute. - - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). - - By.LINK_TEXT: Locate a link element by its exact text. - - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. - - RelativeBy: Locate elements relative to a specified root element. - - Example: - -------- - >>> element = driver.find_elements(By.ID, "foo") + Args: + by: The locating strategy to use. Default is `By.ID`. Supported values include: + - By.ID: Locate by element ID. + - By.NAME: Locate by the `name` attribute. + - By.XPATH: Locate by an XPath expression. + - By.CSS_SELECTOR: Locate by a CSS selector. + - By.CLASS_NAME: Locate by the `class` attribute. + - By.TAG_NAME: Locate by the tag name (e.g., "input", "button"). + - By.LINK_TEXT: Locate a link element by its exact text. + - By.PARTIAL_LINK_TEXT: Locate a link element by partial text match. + - RelativeBy: Locate elements relative to a specified root element. Returns: - ------- - List[WebElement] - list of `WebElements` matching locator strategy found on the page. + List of `WebElements` matching locator strategy found on the page. + + Example: + >>> element = driver.find_elements(By.ID, "foo") """ by, value = self._parent.locator_converter.convert(by, value) return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})["value"] diff --git a/py/selenium/webdriver/safari/options.py b/py/selenium/webdriver/safari/options.py index 5a9ea25cfa4a0..02fce5a2c9740 100644 --- a/py/selenium/webdriver/safari/options.py +++ b/py/selenium/webdriver/safari/options.py @@ -66,48 +66,14 @@ class Options(ArgOptions): SAFARI_TECH_PREVIEW = "Safari Technology Preview" # creating descriptor objects - automatic_inspection = _SafariOptionsDescriptor(AUTOMATIC_INSPECTION, bool) - """Get or Set Automatic Inspection value: + automatic_inspection: bool = _SafariOptionsDescriptor(AUTOMATIC_INSPECTION, bool) + """Whether to enable automatic inspection.""" - Usage: - ------ - - Get - - `self.automatic_inspection` - - Set - - `self.automatic_inspection` = `value` + automatic_profiling: bool = _SafariOptionsDescriptor(AUTOMATIC_PROFILING, bool) + """Whether to enable automatic profiling.""" - Parameters: - ----------- - `value`: `bool` - """ - automatic_profiling = _SafariOptionsDescriptor(AUTOMATIC_PROFILING, bool) - """Get or Set Automatic Profiling value: - - Usage: - ------ - - Get - - `self.automatic_profiling` - - Set - - `self.automatic_profiling` = `value` - - Parameters: - ----------- - `value`: `bool` - """ - use_technology_preview = _SafariOptionsDescriptor(SAFARI_TECH_PREVIEW, bool) - """Get and Set Technology Preview: - - Usage: - ------ - - Get - - `self.use_technology_preview` - - Set - - `self.use_technology_preview` = `value` - - Parameters: - ----------- - `value`: `bool` - """ + use_technology_preview: bool = _SafariOptionsDescriptor(SAFARI_TECH_PREVIEW, bool) + """Whether to use Safari Technology Preview.""" @property def default_capabilities(self) -> dict[str, str]: diff --git a/py/selenium/webdriver/support/expected_conditions.py b/py/selenium/webdriver/support/expected_conditions.py index d17351104612a..2dd80ba8b7d8e 100644 --- a/py/selenium/webdriver/support/expected_conditions.py +++ b/py/selenium/webdriver/support/expected_conditions.py @@ -43,14 +43,11 @@ def title_is(title: str) -> Callable[[WebDriver], bool]: """An expectation for checking the title of a page. - Parameters: - ----------- - title : str - The expected title, which must be an exact match. + Args: + title: The expected title, which must be an exact match. Returns: - ------- - boolean : True if the title matches, False otherwise. + True if the title matches, False otherwise. """ def _predicate(driver: WebDriver): @@ -63,14 +60,11 @@ def title_contains(title: str) -> Callable[[WebDriver], bool]: """An expectation for checking that the title contains a case-sensitive substring. - Parameters: - ----------- - title : str - The fragment of title expected. + Args: + title: The fragment of title expected. Returns: - ------- - boolean : True when the title matches, False otherwise. + True when the title matches, False otherwise. """ def _predicate(driver: WebDriver): @@ -83,21 +77,17 @@ def presence_of_element_located(locator: tuple[str, str]) -> Callable[[WebDriver """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. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. + Args: + locator: Used to find the element. Returns: - ------- - WebElement : The WebElement once it is located. + The WebElement once it is located. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "q"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "q"))) """ def _predicate(driver: WebDriverOrWebElement): @@ -110,14 +100,11 @@ def url_contains(url: str) -> Callable[[WebDriver], bool]: """An expectation for checking that the current url contains a case- sensitive substring. - Parameters: - ----------- - url : str - The fragment of url expected. + Args: + url: The fragment of url expected. Returns: - ------- - boolean : True when the url matches, False otherwise. + True when the url matches, False otherwise. """ def _predicate(driver: WebDriver): @@ -129,18 +116,14 @@ def _predicate(driver: WebDriver): def url_matches(pattern: str) -> Callable[[WebDriver], bool]: """An expectation for checking the current url. - Parameters: - ----------- - pattern : str - The pattern to match with the current url. + Args: + pattern: The pattern to match with the current url. Returns: - ------- - boolean : True when the pattern matches, False otherwise. + True when the pattern matches, False otherwise. - Notes: - ------ - More powerful than url_contains, as it allows for regular expressions. + Note: + More powerful than url_contains, as it allows for regular expressions. """ def _predicate(driver: WebDriver): @@ -152,14 +135,11 @@ def _predicate(driver: WebDriver): def url_to_be(url: str) -> Callable[[WebDriver], bool]: """An expectation for checking the current url. - Parameters: - ----------- - url : str - The expected url, which must be an exact match. + Args: + url: The expected url, which must be an exact match. Returns: - ------- - boolean : True when the url matches, False otherwise. + True when the url matches, False otherwise. """ def _predicate(driver: WebDriver): @@ -172,14 +152,11 @@ def url_changes(url: str) -> Callable[[WebDriver], bool]: """An expectation for checking the current url is different than a given string. - Parameters: - ----------- - url : str - The expected url, which must not be an exact match. + Args: + url: The expected url, which must not be an exact match. Returns: - ------- - boolean : True when the url does not match, False otherwise + True when the url does not match, False otherwise. """ def _predicate(driver: WebDriver): @@ -195,21 +172,17 @@ def visibility_of_element_located( page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. + Args: + locator: Used to find the element. Returns: - ------- - WebElement : The WebElement once it is located and visible. + The WebElement once it is located and visible. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, "q"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, "q"))) """ def _predicate(driver: WebDriverOrWebElement): @@ -225,27 +198,20 @@ def visibility_of(element: WebElement) -> Callable[[Any], Union[Literal[False], """An expectation for checking that an element, known to be present on the DOM of a page, is visible. - Parameters: - ----------- - element : WebElement - The WebElement to check. + Visibility means that the element is not only displayed but also has + a height and width that is greater than 0. + + Args: + element: The WebElement to check. Returns: - ------- - WebElement : The WebElement once it is visible. + The WebElement once it is visible. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> element = WebDriverWait(driver, 10).until(EC.visibility_of(driver.find_element(By.NAME, "q"))) - - Notes: - ------ - 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 + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> element = WebDriverWait(driver, 10).until(EC.visibility_of(driver.find_element(By.NAME, "q"))) """ def _predicate(_): @@ -258,16 +224,12 @@ def _element_if_visible(element: WebElement, visibility: bool = True) -> Union[L """An expectation for checking that an element, known to be present on the DOM of a page, is of the expected visibility. - Parameters: - ----------- - element : WebElement - The WebElement to check. - visibility : bool - The expected visibility of the element. + Args: + element: The WebElement to check. + visibility: The expected visibility of the element. Returns: - ------- - WebElement : The WebElement once it is visible or not visible. + The WebElement once it is visible or not visible. """ return element if element.is_displayed() == visibility else False @@ -276,21 +238,17 @@ def presence_of_all_elements_located(locator: tuple[str, str]) -> Callable[[WebD """An expectation for checking that there is at least one element present on a web page. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. + Args: + locator: Used to find the element. Returns: - ------- - List[WebElement] : The list of WebElements once they are located. + The list of WebElements once they are located. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "foo"))) """ def _predicate(driver: WebDriverOrWebElement): @@ -303,21 +261,17 @@ def visibility_of_any_elements_located(locator: tuple[str, str]) -> Callable[[We """An expectation for checking that there is at least one element visible on a web page. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. + Args: + locator: Used to find the element. Returns: - ------- - List[WebElement] : The list of WebElements once they are located and visible. + The list of WebElements once they are located and visible. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> elements = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> elements = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "foo"))) """ def _predicate(driver: WebDriverOrWebElement): @@ -333,21 +287,17 @@ def visibility_of_all_elements_located( 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. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the elements. + Args: + locator: Used to find the elements. Returns: - ------- - List[WebElement] : The list of WebElements once they are located and visible. + The list of WebElements once they are located and visible. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> elements = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> elements = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "foo"))) """ def _predicate(driver: WebDriverOrWebElement): @@ -367,25 +317,20 @@ def text_to_be_present_in_element(locator: tuple[str, str], text_: str) -> Calla """An expectation for checking if the given text is present in the specified element. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. - text_ : str - The text to be present in the element. + Args: + locator: Used to find the element. + text_: The text to be present in the element. Returns: - ------- - boolean : True when the text is present, False otherwise. + True when the text is present, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_text_in_element = WebDriverWait(driver, 10).until( - EC.text_to_be_present_in_element((By.CLASS_NAME, "foo"), "bar") - ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_text_in_element = WebDriverWait(driver, 10).until( + EC.text_to_be_present_in_element((By.CLASS_NAME, "foo"), "bar") + ) """ def _predicate(driver: WebDriverOrWebElement): @@ -404,25 +349,20 @@ def text_to_be_present_in_element_value( """An expectation for checking if the given text is present in the element's value. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. - text_ : str - The text to be present in the element's value. + Args: + locator: Used to find the element. + text_: The text to be present in the element's value. Returns: - ------- - boolean : True when the text is present, False otherwise. + True when the text is present, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_text_in_element_value = WebDriverWait(driver, 10).until( - ... EC.text_to_be_present_in_element_value((By.CLASS_NAME, "foo"), "bar") - ... ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_text_in_element_value = WebDriverWait(driver, 10).until( + ... EC.text_to_be_present_in_element_value((By.CLASS_NAME, "foo"), "bar") + ... ) """ def _predicate(driver: WebDriverOrWebElement): @@ -443,27 +383,21 @@ def text_to_be_present_in_element_attribute( """An expectation for checking if the given text is present in the element's attribute. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. - attribute_ : str - The attribute to check the text in. - text_ : str - The text to be present in the element's attribute. + Args: + locator: Used to find the element. + attribute_: The attribute to check the text in. + text_: The text to be present in the element's attribute. Returns: - ------- - boolean : True when the text is present, False otherwise. + True when the text is present, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_text_in_element_attribute = WebDriverWait(driver, 10).until( - ... EC.text_to_be_present_in_element_attribute((By.CLASS_NAME, "foo"), "bar", "baz") - ... ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_text_in_element_attribute = WebDriverWait(driver, 10).until( + ... EC.text_to_be_present_in_element_attribute((By.CLASS_NAME, "foo"), "bar", "baz") + ... ) """ def _predicate(driver: WebDriverOrWebElement): @@ -484,25 +418,19 @@ def frame_to_be_available_and_switch_to_it( """An expectation for checking whether the given frame is available to switch to. - Parameters: - ----------- - locator : Union[Tuple[str, str], str, WebElement] - Used to find the frame. + If the frame is available it switches the given driver to the + specified frame. + + Args: + locator: Used to find the frame. Returns: - ------- - boolean : True when the frame is available, False otherwise. + True when the frame is available, False otherwise. Example: - -------- - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("frame_name")) - - Notes: - ------ - If the frame is available it switches the given driver to the - specified frame. + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("frame_name")) """ def _predicate(driver: WebDriver): @@ -524,29 +452,24 @@ def invisibility_of_element_located( """An Expectation for checking that an element is either invisible or not present on the DOM. - Parameters: - ----------- - locator : Union[WebElement, Tuple[str, str]] - Used to find the element. + Args: + locator: Used to find the element. Returns: - ------- - boolean : True when the element is invisible or not present, False otherwise. + True when the element is invisible or not present, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_invisible = WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_invisible = WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((By.CLASS_NAME, "foo"))) - Notes: - ------ - - In the case of NoSuchElement, returns true because the element is not - present in DOM. The try block checks if the element is present but is - invisible. - - In the case of StaleElementReference, returns true because stale element - reference implies that element is no longer visible. + Note: + In the case of NoSuchElement, returns true because the element is not + present in DOM. The try block checks if the element is present but is + invisible. + In the case of StaleElementReference, returns true because stale element + reference implies that element is no longer visible. """ def _predicate(driver: WebDriverOrWebElement): @@ -572,23 +495,19 @@ def invisibility_of_element( """An Expectation for checking that an element is either invisible or not present on the DOM. - Parameters: - ----------- - element : Union[WebElement, Tuple[str, str]] - Used to find the element. + Args: + element: Used to find the element. Returns: - ------- - boolean : True when the element is invisible or not present, False otherwise. + True when the element is invisible or not present, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_invisible_or_not_present = WebDriverWait(driver, 10).until( - ... EC.invisibility_of_element(driver.find_element(By.CLASS_NAME, "foo")) - ... ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_invisible_or_not_present = WebDriverWait(driver, 10).until( + ... EC.invisibility_of_element(driver.find_element(By.CLASS_NAME, "foo")) + ... ) """ return invisibility_of_element_located(element) @@ -599,21 +518,17 @@ def element_to_be_clickable( """An Expectation for checking an element is visible and enabled such that you can click it. - Parameters: - ----------- - mark : Union[WebElement, Tuple[str, str]] - Used to find the element. + Args: + mark: Used to find the element. Returns: - ------- - WebElement : The WebElement once it is located and clickable. + The WebElement once it is located and clickable. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "foo"))) """ # renamed argument to 'mark', to indicate that both locator @@ -633,21 +548,17 @@ def _predicate(driver: WebDriverOrWebElement): def staleness_of(element: WebElement) -> Callable[[Any], bool]: """Wait until an element is no longer attached to the DOM. - Parameters: - ----------- - element : WebElement - The element to wait for. + Args: + element: The element to wait for. Returns: - ------- - boolean : False if the element is still attached to the DOM, true otherwise. + False if the element is still attached to the DOM, true otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_element_stale = WebDriverWait(driver, 10).until(EC.staleness_of(driver.find_element(By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_stale = WebDriverWait(driver, 10).until(EC.staleness_of(driver.find_element(By.CLASS_NAME, "foo"))) """ def _predicate(_): @@ -664,23 +575,19 @@ def _predicate(_): def element_to_be_selected(element: WebElement) -> Callable[[Any], bool]: """An expectation for checking the selection is selected. - Parameters: - ----------- - element : WebElement - The WebElement to check. + Args: + element: The WebElement to check. Returns: - ------- - boolean : True if the element is selected, False otherwise. + True if the element is selected, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_selected = WebDriverWait(driver, 10).until(EC.element_to_be_selected(driver.find_element( - By.CLASS_NAME, "foo")) - ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_selected = WebDriverWait(driver, 10).until(EC.element_to_be_selected(driver.find_element( + By.CLASS_NAME, "foo")) + ) """ def _predicate(_): @@ -692,21 +599,17 @@ def _predicate(_): def element_located_to_be_selected(locator: tuple[str, str]) -> Callable[[WebDriverOrWebElement], bool]: """An expectation for the element to be located is selected. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. + Args: + locator: Used to find the element. Returns: - ------- - boolean : True if the element is selected, False otherwise. + True if the element is selected, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_selected = WebDriverWait(driver, 10).until(EC.element_located_to_be_selected((By.CLASS_NAME, "foo"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_selected = WebDriverWait(driver, 10).until(EC.element_located_to_be_selected((By.CLASS_NAME, "foo"))) """ def _predicate(driver: WebDriverOrWebElement): @@ -718,24 +621,20 @@ def _predicate(driver: WebDriverOrWebElement): def element_selection_state_to_be(element: WebElement, is_selected: bool) -> Callable[[Any], bool]: """An expectation for checking if the given element is selected. - Parameters: - ----------- - element : WebElement - The WebElement to check. - is_selected : bool + Args: + element: The WebElement to check. + is_selected: The expected selection state. Returns: - ------- - boolean : True if the element's selection state is the same as is_selected + True if the element's selection state is the same as is_selected. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_selected = WebDriverWait(driver, 10).until( - ... EC.element_selection_state_to_be(driver.find_element(By.CLASS_NAME, "foo"), True) - ... ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_selected = WebDriverWait(driver, 10).until( + ... EC.element_selection_state_to_be(driver.find_element(By.CLASS_NAME, "foo"), True) + ... ) """ def _predicate(_): @@ -750,24 +649,20 @@ def element_located_selection_state_to_be( """An expectation to locate an element and check if the selection state specified is in that state. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. - is_selected : bool + Args: + locator: Used to find the element. + is_selected: The expected selection state. Returns: - ------- - boolean : True if the element's selection state is the same as is_selected + True if the element's selection state is the same as is_selected. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_selected = WebDriverWait(driver, 10).until(EC.element_located_selection_state_to_be( - (By.CLASS_NAME, "foo"), True) - ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_selected = WebDriverWait(driver, 10).until(EC.element_located_selection_state_to_be( + (By.CLASS_NAME, "foo"), True) + ) """ def _predicate(driver: WebDriverOrWebElement): @@ -783,20 +678,16 @@ def _predicate(driver: WebDriverOrWebElement): def number_of_windows_to_be(num_windows: int) -> Callable[[WebDriver], bool]: """An expectation for the number of windows to be a certain value. - Parameters: - ----------- - num_windows : int - The expected number of windows. + Args: + num_windows: The expected number of windows. Returns: - ------- - boolean : True when the number of windows matches, False otherwise. + True when the number of windows matches, False otherwise. Example: - -------- - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_number_of_windows = WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_number_of_windows = WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) """ def _predicate(driver: WebDriver): @@ -809,21 +700,17 @@ def new_window_is_opened(current_handles: list[str]) -> Callable[[WebDriver], bo """An expectation that a new window will be opened and have the number of windows handles increase. - Parameters: - ----------- - current_handles : List[str] - The current window handles. + Args: + current_handles: The current window handles. Returns: - ------- - boolean : True when a new window is opened, False otherwise. + True when a new window is opened, False otherwise. Example: - -------- - >>> from selenium.webdriver.support.ui import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_new_window_opened = WebDriverWait(driver, 10).until(EC.new_window_is_opened(driver.window_handles)) + >>> from selenium.webdriver.support.ui import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_new_window_opened = WebDriverWait(driver, 10).until(EC.new_window_is_opened(driver.window_handles)) """ def _predicate(driver: WebDriver): @@ -837,18 +724,15 @@ def alert_is_present() -> Callable[[WebDriver], Union[Alert, Literal[False]]]: switching to it. Returns: - ------- - Alert : The Alert once it is located. + The Alert once it is located. Example: - -------- - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> alert = WebDriverWait(driver, 10).until(EC.alert_is_present()) + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> alert = WebDriverWait(driver, 10).until(EC.alert_is_present()) - Notes: - ------ - If the alert is present it switches the given driver to it. + Note: + If the alert is present it switches the given driver to it. """ def _predicate(driver: WebDriver): @@ -864,25 +748,20 @@ def element_attribute_to_include(locator: tuple[str, str], attribute_: str) -> C """An expectation for checking if the given attribute is included in the specified element. - Parameters: - ----------- - locator : Tuple[str, str] - Used to find the element. - attribute_ : str - The attribute to check. + Args: + locator: Used to find the element. + attribute_: The attribute to check. Returns: - ------- - boolean : True when the attribute is included, False otherwise. + True when the attribute is included, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> is_attribute_in_element = WebDriverWait(driver, 10).until( - ... EC.element_attribute_to_include((By.CLASS_NAME, "foo"), "bar") - ... ) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> is_attribute_in_element = WebDriverWait(driver, 10).until( + ... EC.element_attribute_to_include((By.CLASS_NAME, "foo"), "bar") + ... ) """ def _predicate(driver: WebDriverOrWebElement): @@ -898,28 +777,22 @@ def _predicate(driver: WebDriverOrWebElement): def any_of(*expected_conditions: Callable[[D], T]) -> Callable[[D], Union[Literal[False], T]]: """An expectation that any of multiple expected conditions is true. - Parameters: - ----------- - expected_conditions : Callable[[D], T] - The list of expected conditions to check. + Equivalent to a logical 'OR'. Returns results of the first matching + condition, or False if none do. + + Args: + expected_conditions: The list of expected conditions to check. Returns: - ------- - T : The result of the first matching condition, or False if none do. + The result of the first matching condition, or False if none do. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> element = WebDriverWait(driver, 10).until( - ... EC.any_of(EC.presence_of_element_located((By.NAME, "q"), - ... EC.visibility_of_element_located((By.NAME, "q")))) - - Notes: - ------ - Equivalent to a logical 'OR'. Returns results of the first matching - condition, or False if none do. + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> element = WebDriverWait(driver, 10).until( + ... EC.any_of(EC.presence_of_element_located((By.NAME, "q"), + ... EC.visibility_of_element_located((By.NAME, "q")))) """ def any_of_condition(driver: D): @@ -940,29 +813,23 @@ def all_of( ) -> Callable[[D], Union[list[T], Literal[False]]]: """An expectation that all of multiple expected conditions is true. - Parameters: - ----------- - expected_conditions : Callable[[D], Union[T, Literal[False]]] - The list of expected conditions to check. + Equivalent to a logical 'AND'. When any ExpectedCondition is not met, + returns False. When all ExpectedConditions are met, returns a List with + each ExpectedCondition's return value. + + Args: + expected_conditions: The list of expected conditions to check. Returns: - ------- - List[T] : The results of all the matching conditions, or False if any do not. + The results of all the matching conditions, or False if any do not. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> elements = WebDriverWait(driver, 10).until( - ... EC.all_of(EC.presence_of_element_located((By.NAME, "q"), - ... EC.visibility_of_element_located((By.NAME, "q")))) - - Notes: - ------ - 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. + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> elements = WebDriverWait(driver, 10).until( + ... EC.all_of(EC.presence_of_element_located((By.NAME, "q"), + ... EC.visibility_of_element_located((By.NAME, "q")))) """ def all_of_condition(driver: D): @@ -983,27 +850,21 @@ def all_of_condition(driver: D): def none_of(*expected_conditions: Callable[[D], Any]) -> Callable[[D], bool]: """An expectation that none of 1 or multiple expected conditions is true. - Parameters: - ----------- - expected_conditions : Callable[[D], Any] - The list of expected conditions to check. + Equivalent to a logical 'NOT-OR'. + + Args: + expected_conditions: The list of expected conditions to check. Returns: - ------- - boolean : True if none of the conditions are true, False otherwise. + True if none of the conditions are true, False otherwise. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - >>> element = WebDriverWait(driver, 10).until( - ... EC.none_of(EC.presence_of_element_located((By.NAME, "q"), - ... EC.visibility_of_element_located((By.NAME, "q")))) - - Notes: - ------ - Equivalent to a logical 'NOT-OR'. Returns a Boolean + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> element = WebDriverWait(driver, 10).until( + ... EC.none_of(EC.presence_of_element_located((By.NAME, "q"), + ... EC.visibility_of_element_located((By.NAME, "q")))) """ def none_of_condition(driver: D): diff --git a/py/selenium/webdriver/support/wait.py b/py/selenium/webdriver/support/wait.py index 30c20fc862aa4..88c1a276ce1fa 100644 --- a/py/selenium/webdriver/support/wait.py +++ b/py/selenium/webdriver/support/wait.py @@ -40,32 +40,23 @@ def __init__( ): """Constructor, takes a WebDriver instance and timeout in seconds. - Attributes: - ----------- - 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. + Args: + 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.common.by import By - >>> from selenium.webdriver.support.wait import WebDriverWait - >>> from selenium.common.exceptions import ElementNotVisibleException - >>> - >>> # Wait until the element is no longer visible - >>> is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)) - ... .until_not(lambda x: x.find_element(By.ID, "someId").is_displayed()) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.wait import WebDriverWait + >>> from selenium.common.exceptions import ElementNotVisibleException + >>> + >>> # Wait until the element is no longer visible + >>> is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)) + ... .until_not(lambda x: x.find_element(By.ID, "someId").is_displayed()) """ self._driver = driver self._timeout = float(timeout) @@ -90,35 +81,27 @@ def until(self, method: Callable[[D], Union[Literal[False], T]], message: str = Calls the method provided with the driver as an argument until the return value does not evaluate to ``False``. - Parameters: - ----------- - method: callable(WebDriver) - - A callable object that takes a WebDriver instance as an argument. - - message: str - - Optional message for :exc:`TimeoutException` + Args: + method: A callable object that takes a WebDriver instance as an + argument. + message: Optional message for TimeoutException. - Return: - ------- - object: T - - The result of the last call to `method` + Returns: + The result of the last call to `method`. Raises: - ------- - TimeoutException - - If 'method' does not return a truthy value within the WebDriverWait - object's timeout + TimeoutException: If 'method' does not return a truthy value within + the WebDriverWait object's timeout. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - - # Wait until an element is visible on the page - >>> wait = WebDriverWait(driver, 10) - >>> element = wait.until(EC.visibility_of_element_located((By.ID, "exampleId"))) - >>> print(element.text) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> + >>> # Wait until an element is visible on the page + >>> wait = WebDriverWait(driver, 10) + >>> element = wait.until(EC.visibility_of_element_located((By.ID, "exampleId"))) + >>> print(element.text) """ screen = None stacktrace = None @@ -138,39 +121,31 @@ def until(self, method: Callable[[D], Union[Literal[False], T]], message: str = raise TimeoutException(message, screen, stacktrace) def until_not(self, method: Callable[[D], T], message: str = "") -> Union[T, Literal[True]]: - """Wait until the method returns a value that is not False. + """Wait until the method returns a value that is False. Calls the method provided with the driver as an argument until the - return value does not evaluate to ``False``. - - Parameters: - ----------- - method: callable(WebDriver) - - A callable object that takes a WebDriver instance as an argument. + return value evaluates to ``False``. - message: str - - Optional message for :exc:`TimeoutException` + Args: + method: A callable object that takes a WebDriver instance as an + argument. + message: Optional message for TimeoutException. - Return: - ------- - object: T - - The result of the last call to `method` + Returns: + The result of the last call to `method`. Raises: - ------- - TimeoutException - - If 'method' does not return False within the WebDriverWait - object's timeout + TimeoutException: If 'method' does not return False within the + WebDriverWait object's timeout. Example: - -------- - >>> from selenium.webdriver.common.by import By - >>> from selenium.webdriver.support.ui import WebDriverWait - >>> from selenium.webdriver.support import expected_conditions as EC - - # Wait until an element is visible on the page - >>> wait = WebDriverWait(driver, 10) - >>> is_disappeared = wait.until_not(EC.visibility_of_element_located((By.ID, "exampleId"))) + >>> from selenium.webdriver.common.by import By + >>> from selenium.webdriver.support.ui import WebDriverWait + >>> from selenium.webdriver.support import expected_conditions as EC + >>> + >>> # Wait until an element is no longer visible on the page + >>> wait = WebDriverWait(driver, 10) + >>> is_disappeared = wait.until_not(EC.visibility_of_element_located((By.ID, "exampleId"))) """ end_time = time.monotonic() + self._timeout while True: