Selenium error handler

[docs]class ErrorCode: """Error codes defined in the WebDriver wire protocol.""" # Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h SUCCESS = 0 NO_SUCH_ELEMENT = [7, "no such element"] NO_SUCH_FRAME = [8, "no such frame"] NO_SUCH_SHADOW_ROOT = ["no such shadow root"] UNKNOWN_COMMAND = [9, "unknown command"] STALE_ELEMENT_REFERENCE = [10, "stale element reference"] ELEMENT_NOT_VISIBLE = [11, "element not visible"] INVALID_ELEMENT_STATE = [12, "invalid element state"] UNKNOWN_ERROR = [13, "unknown error"] ELEMENT_IS_NOT_SELECTABLE = [15, "element not selectable"] JAVASCRIPT_ERROR = [17, "javascript error"] XPATH_LOOKUP_ERROR = [19, "invalid selector"] TIMEOUT = [21, "timeout"] NO_SUCH_WINDOW = [23, "no such window"] INVALID_COOKIE_DOMAIN = [24, "invalid cookie domain"] UNABLE_TO_SET_COOKIE = [25, "unable to set cookie"] UNEXPECTED_ALERT_OPEN = [26, "unexpected alert open"] NO_ALERT_OPEN = [27, "no such alert"] SCRIPT_TIMEOUT = [28, "script timeout"] INVALID_ELEMENT_COORDINATES = [29, "invalid element coordinates"] IME_NOT_AVAILABLE = [30, "ime not available"] IME_ENGINE_ACTIVATION_FAILED = [31, "ime engine activation failed"] INVALID_SELECTOR = [32, "invalid selector"] SESSION_NOT_CREATED = [33, "session not created"] MOVE_TARGET_OUT_OF_BOUNDS = [34, "move target out of bounds"] INVALID_XPATH_SELECTOR = [51, "invalid selector"] INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, "invalid selector"] ELEMENT_NOT_INTERACTABLE = [60, "element not interactable"] INSECURE_CERTIFICATE = ["insecure certificate"] INVALID_ARGUMENT = [61, "invalid argument"] INVALID_COORDINATES = ["invalid coordinates"] INVALID_SESSION_ID = ["invalid session id"] NO_SUCH_COOKIE = [62, "no such cookie"] UNABLE_TO_CAPTURE_SCREEN = [63, "unable to capture screen"] ELEMENT_CLICK_INTERCEPTED = [64, "element click intercepted"] UNKNOWN_METHOD = ["unknown method exception"] METHOD_NOT_ALLOWED = [405, "unsupported operation"]
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from typing import Any
from typing import Dict
from typing import Type

from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import ElementNotSelectableException
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import ImeActivationFailedException
from selenium.common.exceptions import ImeNotAvailableException
from selenium.common.exceptions import InsecureCertificateException
from selenium.common.exceptions import InvalidArgumentException
from selenium.common.exceptions import InvalidCookieDomainException
from selenium.common.exceptions import InvalidCoordinatesException
from selenium.common.exceptions import InvalidElementStateException
from selenium.common.exceptions import InvalidSelectorException
from selenium.common.exceptions import InvalidSessionIdException
from selenium.common.exceptions import JavascriptException
from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import NoSuchCookieException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
from selenium.common.exceptions import NoSuchShadowRootException
from selenium.common.exceptions import NoSuchWindowException
from selenium.common.exceptions import ScreenshotException
from selenium.common.exceptions import SessionNotCreatedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import UnableToSetCookieException
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.common.exceptions import UnknownMethodException
from selenium.common.exceptions import WebDriverException


[docs]class ErrorCode: """Error codes defined in the WebDriver wire protocol.""" # Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h SUCCESS = 0 NO_SUCH_ELEMENT = [7, "no such element"] NO_SUCH_FRAME = [8, "no such frame"] NO_SUCH_SHADOW_ROOT = ["no such shadow root"] UNKNOWN_COMMAND = [9, "unknown command"] STALE_ELEMENT_REFERENCE = [10, "stale element reference"] ELEMENT_NOT_VISIBLE = [11, "element not visible"] INVALID_ELEMENT_STATE = [12, "invalid element state"] UNKNOWN_ERROR = [13, "unknown error"] ELEMENT_IS_NOT_SELECTABLE = [15, "element not selectable"] JAVASCRIPT_ERROR = [17, "javascript error"] XPATH_LOOKUP_ERROR = [19, "invalid selector"] TIMEOUT = [21, "timeout"] NO_SUCH_WINDOW = [23, "no such window"] INVALID_COOKIE_DOMAIN = [24, "invalid cookie domain"] UNABLE_TO_SET_COOKIE = [25, "unable to set cookie"] UNEXPECTED_ALERT_OPEN = [26, "unexpected alert open"] NO_ALERT_OPEN = [27, "no such alert"] SCRIPT_TIMEOUT = [28, "script timeout"] INVALID_ELEMENT_COORDINATES = [29, "invalid element coordinates"] IME_NOT_AVAILABLE = [30, "ime not available"] IME_ENGINE_ACTIVATION_FAILED = [31, "ime engine activation failed"] INVALID_SELECTOR = [32, "invalid selector"] SESSION_NOT_CREATED = [33, "session not created"] MOVE_TARGET_OUT_OF_BOUNDS = [34, "move target out of bounds"] INVALID_XPATH_SELECTOR = [51, "invalid selector"] INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, "invalid selector"] ELEMENT_NOT_INTERACTABLE = [60, "element not interactable"] INSECURE_CERTIFICATE = ["insecure certificate"] INVALID_ARGUMENT = [61, "invalid argument"] INVALID_COORDINATES = ["invalid coordinates"] INVALID_SESSION_ID = ["invalid session id"] NO_SUCH_COOKIE = [62, "no such cookie"] UNABLE_TO_CAPTURE_SCREEN = [63, "unable to capture screen"] ELEMENT_CLICK_INTERCEPTED = [64, "element click intercepted"] UNKNOWN_METHOD = ["unknown method exception"] METHOD_NOT_ALLOWED = [405, "unsupported operation"]

[docs]class ErrorHandler: """Handles errors returned by the WebDriver server."""

[docs] def check_response(self, response: Dict[str, Any]) -> None: """Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. """ status = response.get("status", None) if not status or status == ErrorCode.SUCCESS: return value = None message = response.get("message", "") screen: str = response.get("screen", "") stacktrace = None if isinstance(status, int): value_json = response.get("value", None) if value_json and isinstance(value_json, str): import json try: value = json.loads(value_json) if len(value.keys()) == 1: value = value["value"] status = value.get("error", None) if not status: status = value.get("status", ErrorCode.UNKNOWN_ERROR) message = value.get("value") or value.get("message") if not isinstance(message, str): value = message message = message.get("message") else: message = value.get("message", None) except ValueError: pass exception_class: Type[WebDriverException] if status in ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status in ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status in ErrorCode.NO_SUCH_SHADOW_ROOT: exception_class = NoSuchShadowRootException elif status in ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status in ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status in ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status in ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif ( status in ErrorCode.INVALID_SELECTOR or status in ErrorCode.INVALID_XPATH_SELECTOR or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER ): exception_class = InvalidSelectorException elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE: exception_class = ElementNotInteractableException elif status in ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = InvalidCookieDomainException elif status in ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = UnableToSetCookieException elif status in ErrorCode.TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status in ErrorCode.UNEXPECTED_ALERT_OPEN: exception_class = UnexpectedAlertPresentException elif status in ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status in ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException elif status in ErrorCode.JAVASCRIPT_ERROR: exception_class = JavascriptException elif status in ErrorCode.SESSION_NOT_CREATED: exception_class = SessionNotCreatedException elif status in ErrorCode.INVALID_ARGUMENT: exception_class = InvalidArgumentException elif status in ErrorCode.NO_SUCH_COOKIE: exception_class = NoSuchCookieException elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN: exception_class = ScreenshotException elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED: exception_class = ElementClickInterceptedException elif status in ErrorCode.INSECURE_CERTIFICATE: exception_class = InsecureCertificateException elif status in ErrorCode.INVALID_COORDINATES: exception_class = InvalidCoordinatesException elif status in ErrorCode.INVALID_SESSION_ID: exception_class = InvalidSessionIdException elif status in ErrorCode.UNKNOWN_METHOD: exception_class = UnknownMethodException else: exception_class = WebDriverException if not value: value = response["value"] if isinstance(value, str): raise exception_class(value) if message == "" and "message" in value: message = value["message"] screen = None # type: ignore[assignment] if "screen" in value: screen = value["screen"] stacktrace = None st_value = value.get("stackTrace") or value.get("stacktrace") if st_value: if isinstance(st_value, str): stacktrace = st_value.split("n") else: stacktrace = [] try: for frame in st_value: line = frame.get("lineNumber", "") file = frame.get("fileName", "<anonymous>") if line: file = f"{file}:{line}" meth = frame.get("methodName", "<anonymous>") if "className" in frame: meth = f"{frame['className']}.{meth}" msg = " at %s (%s)" msg = msg % (meth, file) stacktrace.append(msg) except TypeError: pass if exception_class == UnexpectedAlertPresentException: alert_text = None if "data" in value: alert_text = value["data"].get("text") elif "alert" in value: alert_text = value["alert"].get("text") raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here raise exception_class(message, screen, stacktrace)

Classes

ErrorCode Error codes defined in the WebDriver wire protocol.
ErrorHandler Handles errors returned by the WebDriver server.
class selenium.webdriver.remote.errorhandler.ErrorCode[source]

Error codes defined in the WebDriver wire protocol.

ELEMENT_CLICK_INTERCEPTED = [64, ‘element click intercepted’]
ELEMENT_IS_NOT_SELECTABLE = [15, ‘element not selectable’]
ELEMENT_NOT_INTERACTABLE = [60, ‘element not interactable’]
ELEMENT_NOT_VISIBLE = [11, ‘element not visible’]
IME_ENGINE_ACTIVATION_FAILED = [31, ‘ime engine activation failed’]
IME_NOT_AVAILABLE = [30, ‘ime not available’]
INSECURE_CERTIFICATE = [‘insecure certificate’]
INVALID_ARGUMENT = [61, ‘invalid argument’]
INVALID_COOKIE_DOMAIN = [24, ‘invalid cookie domain’]
INVALID_COORDINATES = [‘invalid coordinates’]
INVALID_ELEMENT_COORDINATES = [29, ‘invalid element coordinates’]
INVALID_ELEMENT_STATE = [12, ‘invalid element state’]
INVALID_SELECTOR = [32, ‘invalid selector’]
INVALID_SESSION_ID = [‘invalid session id’]
INVALID_XPATH_SELECTOR = [51, ‘invalid selector’]
INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, ‘invalid selector’]
JAVASCRIPT_ERROR = [17, ‘javascript error’]
METHOD_NOT_ALLOWED = [405, ‘unsupported operation’]
MOVE_TARGET_OUT_OF_BOUNDS = [34, ‘move target out of bounds’]
NO_ALERT_OPEN = [27, ‘no such alert’]
NO_SUCH_COOKIE = [62, ‘no such cookie’]
NO_SUCH_ELEMENT = [7, ‘no such element’]
NO_SUCH_FRAME = [8, ‘no such frame’]
NO_SUCH_SHADOW_ROOT = [‘no such shadow root’]
NO_SUCH_WINDOW = [23, ‘no such window’]
SCRIPT_TIMEOUT = [28, ‘script timeout’]
SESSION_NOT_CREATED = [33, ‘session not created’]
STALE_ELEMENT_REFERENCE = [10, ‘stale element reference’]
SUCCESS = 0
TIMEOUT = [21, ‘timeout’]
UNABLE_TO_CAPTURE_SCREEN = [63, ‘unable to capture screen’]
UNABLE_TO_SET_COOKIE = [25, ‘unable to set cookie’]
UNEXPECTED_ALERT_OPEN = [26, ‘unexpected alert open’]
UNKNOWN_COMMAND = [9, ‘unknown command’]
UNKNOWN_ERROR = [13, ‘unknown error’]
UNKNOWN_METHOD = [‘unknown method exception’]
XPATH_LOOKUP_ERROR = [19, ‘invalid selector’]
class selenium.webdriver.remote.errorhandler.ErrorHandler[source]

Handles errors returned by the WebDriver server.

check_response(response: Dict[str, Any]) → None[source]

Checks that a JSON response from the WebDriver does not have an
error.

Args:
  • response — The JSON response from the WebDriver server as a dictionary
    object.
Raises:

If the response contains an error message.

# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # «License»); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Any from typing import Dict from typing import Type from selenium.common.exceptions import ElementClickInterceptedException from selenium.common.exceptions import ElementNotInteractableException from selenium.common.exceptions import ElementNotSelectableException from selenium.common.exceptions import ElementNotVisibleException from selenium.common.exceptions import ImeActivationFailedException from selenium.common.exceptions import ImeNotAvailableException from selenium.common.exceptions import InsecureCertificateException from selenium.common.exceptions import InvalidArgumentException from selenium.common.exceptions import InvalidCookieDomainException from selenium.common.exceptions import InvalidCoordinatesException from selenium.common.exceptions import InvalidElementStateException from selenium.common.exceptions import InvalidSelectorException from selenium.common.exceptions import InvalidSessionIdException from selenium.common.exceptions import JavascriptException from selenium.common.exceptions import MoveTargetOutOfBoundsException from selenium.common.exceptions import NoAlertPresentException from selenium.common.exceptions import NoSuchCookieException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoSuchFrameException from selenium.common.exceptions import NoSuchShadowRootException from selenium.common.exceptions import NoSuchWindowException from selenium.common.exceptions import ScreenshotException from selenium.common.exceptions import SessionNotCreatedException from selenium.common.exceptions import StaleElementReferenceException from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import UnableToSetCookieException from selenium.common.exceptions import UnexpectedAlertPresentException from selenium.common.exceptions import UnknownMethodException from selenium.common.exceptions import WebDriverException class ErrorCode: «»»Error codes defined in the WebDriver wire protocol.»»» # Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h SUCCESS = 0 NO_SUCH_ELEMENT = [7, «no such element»] NO_SUCH_FRAME = [8, «no such frame»] NO_SUCH_SHADOW_ROOT = [«no such shadow root»] UNKNOWN_COMMAND = [9, «unknown command»] STALE_ELEMENT_REFERENCE = [10, «stale element reference»] ELEMENT_NOT_VISIBLE = [11, «element not visible»] INVALID_ELEMENT_STATE = [12, «invalid element state»] UNKNOWN_ERROR = [13, «unknown error»] ELEMENT_IS_NOT_SELECTABLE = [15, «element not selectable»] JAVASCRIPT_ERROR = [17, «javascript error»] XPATH_LOOKUP_ERROR = [19, «invalid selector»] TIMEOUT = [21, «timeout»] NO_SUCH_WINDOW = [23, «no such window»] INVALID_COOKIE_DOMAIN = [24, «invalid cookie domain»] UNABLE_TO_SET_COOKIE = [25, «unable to set cookie»] UNEXPECTED_ALERT_OPEN = [26, «unexpected alert open»] NO_ALERT_OPEN = [27, «no such alert»] SCRIPT_TIMEOUT = [28, «script timeout»] INVALID_ELEMENT_COORDINATES = [29, «invalid element coordinates»] IME_NOT_AVAILABLE = [30, «ime not available»] IME_ENGINE_ACTIVATION_FAILED = [31, «ime engine activation failed»] INVALID_SELECTOR = [32, «invalid selector»] SESSION_NOT_CREATED = [33, «session not created»] MOVE_TARGET_OUT_OF_BOUNDS = [34, «move target out of bounds»] INVALID_XPATH_SELECTOR = [51, «invalid selector»] INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, «invalid selector»] ELEMENT_NOT_INTERACTABLE = [60, «element not interactable»] INSECURE_CERTIFICATE = [«insecure certificate»] INVALID_ARGUMENT = [61, «invalid argument»] INVALID_COORDINATES = [«invalid coordinates»] INVALID_SESSION_ID = [«invalid session id»] NO_SUCH_COOKIE = [62, «no such cookie»] UNABLE_TO_CAPTURE_SCREEN = [63, «unable to capture screen»] ELEMENT_CLICK_INTERCEPTED = [64, «element click intercepted»] UNKNOWN_METHOD = [«unknown method exception»] METHOD_NOT_ALLOWED = [405, «unsupported operation»] class ErrorHandler: «»»Handles errors returned by the WebDriver server.»»» def check_response(self, response: Dict[str, Any]) -> None: «»»Checks that a JSON response from the WebDriver does not have an error. :Args: — response — The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. «»» status = response.get(«status», None) if not status or status == ErrorCode.SUCCESS: return value = None message = response.get(«message», «») screen: str = response.get(«screen», «») stacktrace = None if isinstance(status, int): value_json = response.get(«value», None) if value_json and isinstance(value_json, str): import json try: value = json.loads(value_json) if len(value.keys()) == 1: value = value[«value»] status = value.get(«error», None) if not status: status = value.get(«status», ErrorCode.UNKNOWN_ERROR) message = value.get(«value») or value.get(«message») if not isinstance(message, str): value = message message = message.get(«message») else: message = value.get(«message», None) except ValueError: pass exception_class: Type[WebDriverException] if status in ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status in ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status in ErrorCode.NO_SUCH_SHADOW_ROOT: exception_class = NoSuchShadowRootException elif status in ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status in ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status in ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status in ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif ( status in ErrorCode.INVALID_SELECTOR or status in ErrorCode.INVALID_XPATH_SELECTOR or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER ): exception_class = InvalidSelectorException elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE: exception_class = ElementNotInteractableException elif status in ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = InvalidCookieDomainException elif status in ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = UnableToSetCookieException elif status in ErrorCode.TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status in ErrorCode.UNEXPECTED_ALERT_OPEN: exception_class = UnexpectedAlertPresentException elif status in ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status in ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException elif status in ErrorCode.JAVASCRIPT_ERROR: exception_class = JavascriptException elif status in ErrorCode.SESSION_NOT_CREATED: exception_class = SessionNotCreatedException elif status in ErrorCode.INVALID_ARGUMENT: exception_class = InvalidArgumentException elif status in ErrorCode.NO_SUCH_COOKIE: exception_class = NoSuchCookieException elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN: exception_class = ScreenshotException elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED: exception_class = ElementClickInterceptedException elif status in ErrorCode.INSECURE_CERTIFICATE: exception_class = InsecureCertificateException elif status in ErrorCode.INVALID_COORDINATES: exception_class = InvalidCoordinatesException elif status in ErrorCode.INVALID_SESSION_ID: exception_class = InvalidSessionIdException elif status in ErrorCode.UNKNOWN_METHOD: exception_class = UnknownMethodException else: exception_class = WebDriverException if not value: value = response[«value»] if isinstance(value, str): raise exception_class(value) if message == «» and «message» in value: message = value[«message»] screen = None # type: ignore[assignment] if «screen» in value: screen = value[«screen»] stacktrace = None st_value = value.get(«stackTrace») or value.get(«stacktrace») if st_value: if isinstance(st_value, str): stacktrace = st_value.split(«n«) else: stacktrace = [] try: for frame in st_value: line = frame.get(«lineNumber», «») file = frame.get(«fileName», «<anonymous>») if line: file = {file}:{line}« meth = frame.get(«methodName», «<anonymous>») if «className» in frame: meth = {frame[‘className’]}.{meth}« msg = » at %s (%s)» msg = msg % (meth, file) stacktrace.append(msg) except TypeError: pass if exception_class == UnexpectedAlertPresentException: alert_text = None if «data» in value: alert_text = value[«data»].get(«text») elif «alert» in value: alert_text = value[«alert»].get(«text») raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here raise exception_class(message, screen, stacktrace)

14 Oct 2018

Selenium is a very versatile web scraping tool that is accessible via multiple programming languages.

It’s distinguished from text-parsing scrapers like BeautifulSoup as it actually simulates a web navigation experience, enabling you to scrape website running on a lot of Javascript and iframes.

That makes Selenium especially powerful when you are in need of scraping large websites, like e-commerce sites.

However, as with large websites, the pages you scrape won’t be totally identical with one another.

Hence, error or exception handling is very, very important.

Without proper exception handling, you may face errors after errors and waste time, as any error will simply halt your scraping work.

This is especially bad when you have set up your scraping task to take place over lunch or overnight.

Missing Element

Sometimes, certain pages do not have a certain element, which is very common.

For example, you might be scraping Amazon for products’ reviews. Some products that do not have any reviews simply do not have any review element to show you.

This can be easily solved by appending a «» or None to the list that you’re populating your scrape result.

from selenium.common.exceptions import NoSuchElementException

reviews = []

for page in pages_to_scrape:
  try:
    # Insert your scraping action here
    reviews.append(driver.find_element_by_css_selector('div.review').text)
  except NoSuchElementException:
    # Just append a None or ""
    reviews.append(None)
    

Timeout Exception

Some websites are simply slow or too small that your scraping has caused their server to overload.

The latter is always bad and you shouldn’t crash other people’s websites when scraping.

In any case, timeouts (i.e. page failed to load) are common on large websites.

However, I won’t recommend catching this error unless you know from experience that the website is prone to timeouts. It can be a huge waste of resource if the website has a 0.01% chance of timeout.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

driver.get("your url")
# Remove the while loop and break if you don't want to try again when it took too long
while True:
  try:
    # Define an element that you can start scraping when it appears
    # If the element appears after 5 seconds, break the loop and continue
    WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, "your selector")))
    break
  except TimeoutException:
    # If the loading took too long, print message and try again
    print("Loading took too much time!")

Element Click Intercepted Exception

This error happens when the element you try to click (e.g. the «next page» button) gets blocked by another element and becomes unclickable.

The common cause of this is a pop-up being triggered, or there is a chat box that appears at the bottom-right of the page.

There are a few ways to solve this. The first way is to close the pop-up.

from selenium.common.exceptions import ElementClickInterceptedException

try:
  # Tries to click an element
  driver.find_element_by_css_selector("button selector").click()
except ElementClickInterceptedException:
  # If pop-up overlay appears, click the X button to close
  time.sleep(2) # Sometimes the pop-up takes time to load
  driver.find_element_by_css_selector("close button selector").click()

You may also use Javascript to hide that element (credit to Louis’ StackOverflow answer):

from selenium.common.exceptions import ElementClickInterceptedException

try:
  # Tries to click an element
  driver.find_element_by_css_selector("button selector").click()
except ElementClickInterceptedException:
  element = driver.find_element_by_class_name("blocking element's class")
  driver.execute_script("""
            var element = arguments[0];
            element.parentNode.removeChild(element);
            """, element)

If it’s not a pop-up, the problem could be solved by scrolling away, hoping that the blocking element moves with you and away from the button/link to be clicked.

from selenium.common.exceptions import ElementClickInterceptedException

try:
  # Tries to click an element
  driver.find_element_by_css_selector("button selector").click()
except ElementClickInterceptedException:
  # Use Javascript to scroll down to bottom of page
  driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Stale Element

Stale element happens when the element is was deleted or no longer attached to the DOM. 

Though a not very common error, some websites are prone to having this error.

When encountered with this error, you can just try again for a number of times.

from selenium.common.exceptions import StaleElementReferenceException

while True:    
  try:
    item_list.append(driver.find_element_by_id("item id").text)
  except StaleElementReferenceException:
    continue # If StaleElement appears, try again
  break # once try is successful, stop while loop

Best Practice — Error Handling & Exceptions

Only use necessary error exceptions

Catching errors and using these exceptions slows your code down significantly. It can cause a regular 1-hour scraping task to double in time especially if you wrap all your scraping actions with error exceptions.

Sometimes it’s totally inescapable, and that’s when a full coverage of error exceptions is necessary so that you can run it overnight without any worries.

However, I recommend to do a trial and error on your code and implement error exceptions only when you encounter them.

Start with a small, representative sample of your web pages to find out the type of errors that can happen.

Use placeholder element before appending to a list

If you’re scraping a few elements in a row, it’s best to assign the result of the scrape to a temporary, placeholder variable before appending to a list.

This is because if you’re appending all to their respective lists, an error in the later stages will cause your prior appended lists having more elements.

# ====================
# Use this way
# ====================
try:
  item_one_temp = driver.find_element_by_id("item one id").text
  item_two_temp = driver.find_element_by_id("item two id").text
  item_one.append(item_one_temp)
  item_two.append(item_two_temp)
except NoSuchElementException:
  item_one.append(None)
  item_two.append(None)

# ====================
# Instead of this
# ====================
try:
  item_one.append(driver.find_element_by_id("item one id").text)
  # if the next element does not exist, item_one list is already appended
  # i.e. one of your list is longer than another
  item_two.append(driver.find_element_by_id("item two id").text)
except NoSuchElementException:
  item_one.append(None)
  item_two.append(None)

Specify specific errors, unless your action plan for any error is the same

It’s useful to specify specific errors that you expect as different errors require different treatments.

Only use a broad «except» statements if you’re planning to do the same if any error arises.

I wish that I know all this before I started scraping as I had to waste a lot of time on StackOverflow. Hope this guide has been useful :)

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

Exception handling is not new and it is the process of responding to the occurrence of exceptions that may happen during execution of our program.

For example, when we are trying to click on an element which is not at all displayed on the browser, will cause our program to throw exception altering the expected flow.
Addition to the flow alteration, exceptions can crash the system and forbid next valid statements to get executed.

The exception classes are available in selenium.common.exceptions package and can be imported like this

Syntax:
from selenium.common.exceptions import [Exception Name]

Example:

from selenium.common.exceptions import NoSuchElementException

For example, we have a html page in which we need to find element with id attribute ‘privacy-policy’.

<html>
    <body>
      <form id='sigupForm'>
	Username: <input name='username' type='text'/><br/>
	Password: <input name='password' type='password'/><br/>
	<input id='privacypolicy' name='privacypolicy' type='checkbox'>Accept Privacy Policy</input><br/>
	<input id='termsconditions' name='termscondition' type='checkbox'>Accept Terms and Condition</input><br/>
	<input type='button' value='Submit'></input>
      </form>
    </body>
</html>
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox(executable_path="[Firefox driver path]")
driver.get("[URL to open]")

webElement = driver.find_element_by_id("privacy-policy")
webElement.click()

But due to some changes id attribute has been changed to ‘privacypolicy’ in which case our tests will fail with below exception and our tests will fail.

File "ExceptionHandling.py", line 7, in 
    driver.find_element_by_id("privacy-policy");
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 341, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 855, in find_element
    'value': value})['value']
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="privacy-policy"]

In order to ensure that our test fails with proper error message we need to capture ‘NoSuchElementException’ and print appropriate log message.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox(executable_path="[Firefox driver path]")
driver.get("[URL to open]")

try:
    webElement = driver.find_element_by_id("privacy-policy")
    webElement.click()
except NoSuchElementException as exception:
    print "Element not found and test failed"

Output:

allselenium$ python exception-handling.py
Element not found and test failed
allselenium$ 

 python selenium Exception handling

Today we are going to discuss the scenario to handle error message in Selenium. Defect, Bug, Error– All these are synonyms to each other and refer to the same meaning, that is, the un-expected working of the system. Software testing is all about finding a defect (bug) and reporting to the respective developer to make it fixed based on its priority and severity level.

A defect (bug) only occurs when there is a mismatch between the Actual result and the Expected result. In case of manual testing or Functional testing, we follow comparison technique to mark any bug a defect. Hence, we will follow the same principle of comparison between the expected and the actual test result to align the scenario with a defect or not a defect.

The technique will be the same everywhere; we only have to write the manual technique in the programming language. So in Selenium with Java, we use any of the comparison operators or methods or statements to identify any mismatches between actual and expected test results. Therefore, based on the observation we can print pass or fail in test report as well as we can send log which will be printed in the console.

What are the available logics to handle error message in Selenium?

We have three techniques that we can use to compare the expected test result and actual test result. It depends on the conscience of the Automation engineer to use the technique. So here are those three techniques:

  • Comparison using Ternary operator
  • Comparison using if-else statement
  • Comparison using Java Assertion or Selenium Assertion

You can use which among the above looks perfect for your business scenario. I will explain each one of them separately so that you don’t have any difficulty in making your choice. Hence, let’s start with the ternary operator.

Handle error message in Selenium

Comparison using Ternary operator

Ternary operator has three statements, like-

(conditions) ? “if the condition is true then execute this code” : “if the condition is false then execute this” ;

This is the sample statement of Ternary operator. At the place of conditions, you can mention the comparison between actual and expected. Following sample code is the best example of uses of the ternary operator. Here we are using getTitle() method to store the title of the web page, further, we placed hardcoded expected title in the string. We are comparing both the strings and putting them in Ternary operator. See the code snippet below:

package SeleniumTester;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class ErrorMessageDemo {
  @Test
  public void errorMessageDemo() {
	  
	  System.setProperty("webdriver.chrome.driver", "C:\Selenium\chromedriver.exe");
	  
	  WebDriver driver = new ChromeDriver();
	 
	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	  
	  driver.get("https://www.inviul.com");
	  
	  driver.manage().window().maximize();
	  
          //Expected Title
	  String expectedTitle = "Free Selenium Tutorials by Avinash Mishrda";
	  //Actual Title
	  String actualTitle = driver.getTitle();

	  //Conditions
	  boolean t = (actualTitle.equals(expectedTitle));

	  //Ternary Operator Definition
	  String result = (t==true) ? "Title Matched" :  "Title didn't match";
	  
	  System.out.println("Result is- "+result);
	  
	  driver.close();
	  
	  driver.quit();
  }
}

Comparison using if-else statement

If-Else statement is the further expansion of the Ternary operator. If you are not comfortable with ternary operator then you can simply use if-else statement. So within ‘If’ statement the conditional logic for comparison will be written. If this logic is true then statements written inside if statement will be executed, otherwise, else statement will be executed. This is how you can do a comparison between actual and expected results. See code snippet below:

package SeleniumTester;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class ErrorMessageDemo {
  @Test
  public void errorMessageDemo() {
	  
	  System.setProperty("webdriver.chrome.driver", "C:\Selenium\chromedriver.exe");
	  
	  WebDriver driver = new ChromeDriver();
	 
	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	  
	  driver.get("https://www.inviul.com");
	  
	  driver.manage().window().maximize();
	  
	  //Expected Title
	  String expectedTitle = "Free Selenium Tutorials by Avinash Mishrda";
	  
	  //Actual Title
	  String actualTitle = driver.getTitle();
	  
	  //Conditions
	  if(actualTitle.equals(expectedTitle)){
		  
		  System.out.println("Title Matched");
		  
	  }else {
		  
		  System.out.println("Title didn't match");
	  }
	  
	  driver.close();
	  
	  driver.quit();
  }
}

Comparison using Java Assertion or Selenium Assertion

This is an advanced yet effective technique to identify pass or fail criteria of any test case in Selenium WebDriver. It also has the good impact to handle error message in Selenium. I will have a separate tutorial on Assertions in Selenium, but for this time being, let me tell you the use of assertTrue() method here.

Assert.assertTrue(conditions, “Message on failure”);

Here we have to define the conditions to check the failure of the particular scenario if the scenario fails then assertTrue will send a pre-defined message to the console. See the code snippet below with screenshot from the console:

package SeleniumTester;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ErrorMessageDemo {
  @Test
  public void errorMessageDemo() {
	  
	  System.setProperty("webdriver.chrome.driver", "C:\Selenium\chromedriver.exe");
	  
	  WebDriver driver = new ChromeDriver();
	 
	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	  
	  driver.get("https://www.inviul.com");
	  
	  driver.manage().window().maximize();
	  
	  //Expected Title 
          String expectedTitle = "Free Selenium Tutorials by Avinash Mishrda"; 

          //Actual Title 
          String actualTitle = driver.getTitle(); 

          //Conditions 
          boolean t = (actualTitle.equals(expectedTitle));
	 
	  //Assertions
	   Assert.assertTrue(t, "Title didn't match");
	  
	  driver.close();
	  
	  driver.quit();
  }
}

Handle error message in Selenium

These three techniques are the best techniques to handle error message in Selenium WebDriver. We took title comparison as a referential example to guide you. Suppose a scenario where you are getting some error message then in such situation select the entire error message and define a dynamic XPath for it, then use getText() method to capture the error message. Further, you can do comparisons in Boolean conditions. You can use above techniques further to handle the error message.

Hope this tutorial guide you properly to define the pass-fail criteria of any test cases in Selenium. See you in the next tutorial.

Happy Learning. 🙂

About The Author

Avinash Mishra

Avinash Mishra is the author of Inviul blog. He is a software engineer and blogger by choice. He loves to write blogs, and apart from blogging, he is interested in documentary film making, listening to music, traveling around the world and philanthropic activities.

With the world evolving towards software development, testing plays a vital role in making the process defect free. Selenium is one such tool that helps in finding bugs and resolve them. The Selenium Certification can help you learn all about exceptions. Exceptions in Selenium is an important concept that helps us in handling errors and avoid software failures. Through this article on Exceptions in Selenium, I will give you a complete insight into the fundamentals and various methods of handling exceptions.

In this article, I will be covering the following topics.

  • Introduction to Exception Handling
  • Checked vs Unchecked Exception
  • Basic Example of Exception
  • Types of Exceptions
  • Methods of Handling Exceptions

You may also go through this recording of Exceptions in Selenium by our Experts where you can understand the topics in a detailed manner with examples.

Handle Exceptions in Selenium Webdriver | Popular Selenium Exceptions | Edureka


This video will talk about exception handling in selenium. It will also tell you about various types of exceptions and how to handle them using various methods.

Introduction to Exceptions

An exception is an event or a problem that arises during the execution of a program. When an exception occurs, the normal flow of program halts and an exception object is created. The program then tries to find someone that can handle the raised exception. The exception object contains a lot of debugging information, such as method hierarchy, the line number where the exception occurred, the type of exception, etc.

When you start working with Selenium webdriver, you will come across different exceptions based on the code you write. The same code some times work properly and sometimes it simply doesn’t. Whenever you develop any script, you try to give the best quality code that works fine. But Unfortunately, sometimes exceptions come as side effects to the scripts that we develop and tends to fail. That’s why handling an exception is very important.

Exception flow - Exceptions in Selenium - EdurekaException Handling mechanism follows a flow which is depicted in the above figure. But if an exception is not handled, it may lead to a system failure. That is why handling an exception is very important. Now let’s move further and understand what are the various categories of exceptions. 

Checked vs Unchecked Exception

Basically, there are 2 types of exceptions in Selenium and they are as follows:

  • Checked Exception
  • Unchecked Exception

Let’s understand these two exceptions in depth.

  • Checked Exception
    It is an exception that occurs at compile time, also called compile time exceptions. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
  • Unchecked Exception
    It is an exception that occurs at the time of execution and is called Runtime Exceptions. In C++, all exceptions are unchecked, but in Java, exceptions can be either checked or unchecked. So, it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to specify or catch the exceptions.

Basic Example of Exception

class Exception{
public static void main(String args[]){
try{
//code that may raise an exception</span>
}
catch(Exception e){
// rest of the program
}
}
}

Above code represent an exception wherein inside try block we are going to write a code that may raise an exception and then, that exception will be handled in the catch block. Having understood this, let’s move further and see different types of exceptions that cause disruption to the normal flow of execution of the program.

Types of Exceptions

  • WebDriverException

WebDriver Exception comes when we try to perform any action on the non-existing driver.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.close();
driver.quit();
  • NoAlertPresentException

When we try to perform an action i.e., either accept() or dismiss() which is not required at a required place; gives us this exception.

try{
driver.switchTo().alert().accept();
}
catch (NoAlertPresentException E){
E.printStackTrace();
}
  • NoSuchWindowException

When we try to switch to a window which is not present gives us this exception:

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().window("Yup_Fail");
driver.close();

In the above snippet, line 3 throws us an exception, as we are trying to switch to a window that is not present.

  • NoSuchFrameException

Similar to Window exception, Frame exception mainly comes during switching between the frames.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().frame("F_fail");
driver.close();

In the above snippet, line 3 throws us an exception, as we are trying to switch to a frame that is not present.

  • NoSuchElementException

This exception is thrown when we WebDriver doesn’t find the web-element in the DOM.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.findElement(By.name("fake")).click();

Now see move ahead in this exceptions in Selenium article and see various methods used to handle Exceptions.

Methods of Handling Exceptions

  1. Try: try block is used to enclose the code that might throw an exception.
  2. Catch: catch block is used to handle the Exception. It must be used after the try block only
  3. Finally: finally block is a block that is used to execute important code such as closing connection, stream etc. It is always executed whether an exception is handled or not.
  4. Throw: throw” keyword is used to throw an exception.

Throws: The “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Find out our Selenium Testing Course in Top Cities

India United States Other Countries
Selenium Training in India Selenium Training in Chicago Selenium Certification UK
Selenium Training in Mumbai Selenium Training in New York Selenium Training in Singapore
Selenium Course in Hyderabad Selenium Training in USA Selenium Training Sydney

Let’s see a small example to understand how a thrown exception can be handled using exception methods. Let’s have a look at the code.

package Edureka;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Exceptionhandling {
public static void main(String[] args) throws InterruptedException, TimeoutException{
System.setProperty("webdriver.firefox.driver", "C:Selenium-java-edurekachromedriver_win32chromedriver.exe");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("https://www.google.com");
try{
driver.findElement(By.xpath("//*[@id='register']")).click();
}catch (Exception e) {
System.out.println("Register element is not found.");
throw(e);
}
System.out.println("Hello");
}
}

Let’s understand the functionalities of each method in depth.

Try Method

In the above code, I have used a try block to enter the statement that throws the exception. Here, this statement driver.findElement(By.xpath(“//*[@id=’register’]”)).click(); throws exception because in the Google Search page Selenium cannot locate the particular element. So, once the exception is thrown, the normal execution of the program will be interrupted. Now, let’s see how it is handled in the catch block.

Catch Method

The task here is to handle this exception and continue the execution of the program. For that, I have written a catch block which will handle the thrown exception. It should always be written after the try block. So when you execute the program, it will print the rest of the statements.

Throw Method

As you all know throw is a keyword which is used to pass an exception. But, the interesting thing is that irrespective of the fact that catch block has handled the exception or not, throw()will still raise an exception. This results in disrupting the normal flow of execution of the program. In the above code, after the catch block has handled the exception,  I have written a statement throw(e); to throw an exception.

Throws Method

Throws declaration is used to declare an exception. For example, It can declare Interrupted exception, timeout exception, etc. This is how various methods can be used to handle the raised exception in the program.

With this, we come to an end of this article on Exceptions in Selenium. I hope you understood the concepts and helped in adding value to your knowledge.

If you wish to learn Selenium and build a career in the testing domain, then check out our interactive, live-online Selenium Certification, that comes with 24*7 support to guide you throughout your learning period.

Got a question for us? Please mention it in the comments section of Exceptions in Selenium article and we will get back to you.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Selenium common exceptions webdriverexception message unknown error cannot find chrome binary
  • Selenium automation error
  • Selected boot image did not authenticate как исправить
  • Select variable to plot матлаб как исправить ошибку
  • Select error ora 01722 invalid number

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии