-1

I have a code similar to this:

def number_of_doors():
   try:
      return WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".number .doors"))).text
   except:
      return False

def number_of_windows():
   try:
      return WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".number .windows"))).text
   except:
      return False

if number_of_doors() == number_of_windows():
   print('Doors and windows matched')
elif number_of_doors() != number_of_windows():
   print('Doors and windows not matched')
elif number_of_doors() is False:
   print('Doors not found')

I've been told that it is a bad practice to have string in the try and boolean in the except? If so what could be a better (correct) solution?

2
  • Do you want your code to proceed if not doors or windows are found?
    – vitaliis
    Commented Apr 22, 2021 at 15:17
  • Yes, no matter what I want my code to proceed forward.
    – bbfl
    Commented Apr 23, 2021 at 5:19

3 Answers 3

1

Here you can simply return an empty string instead of Boolean False in except:

1
  • 1
    Thanks, yeah for now seems this is the most relevant answer so I just changed except: return False to except: return 'Error' (for example)
    – bbfl
    Commented Apr 26, 2021 at 10:55
0

I don't think you should use try/catch in this case at all. Just return the text of an element.

def number_of_doors():
    WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".number .doors")))
    return driver.find_element_by_css_selector(".number .doors").text


def number_of_windows():
    WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".number .windows")))
    return driver.find_element_by_css_selector(".number .windows").text


if number_of_doors() == number_of_windows():
    print('Doors and windows matched')
elif number_of_doors() != number_of_windows():
    print('Doors and windows not matched')

TimeoutException will be thrown by WebDriverWait if an element is not found. Your code also had indentation problems.

3
  • Thanks for the advice but I forgot to say that if element is not found I want the code to proceed and not TimeoutException to be thrown.
    – bbfl
    Commented Apr 23, 2021 at 5:20
  • OK, did you find the solution?
    – vitaliis
    Commented Apr 23, 2021 at 15:20
  • well, not really only obvious solution (if I want to avoid boolean) is to use string in the like this: except: return 'Error'
    – bbfl
    Commented Apr 26, 2021 at 10:54
0

I would imagine that it would be more simple to test for return values from the function itself. If you are expecting it to not be None, or Null it would be much easier to test this way:

from selenium.webdriver import WebDriverWait
import selenium.common.exceptions


def number_of_doors():
    try:
        doors = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".number .doors"))).text
        windows = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".number .windows"))).text
        if doors is not None and windows is not None:
            # return true or false, and a test of if they match or not. you can adjust this as needed, but this will check if both values contain anything.
            return {
                "Success": True,
                "Do_They_Match": doors == windows
            }
        else:
            # Since we only care about a True value being in success, return it as false, and do they match as a none type.
            return {
                "Success": False,
                "Do_They_Match": None,
                "Error": None,
                "Error_Message": None
            }
    except (selenium.common.exceptions, Exception) as e:
        # Return a dict object, and be able to pull out values you would absolutely need. Error information, success value, and do they match being none as nothing was tested.
        return {
            "Success": False,
            "Do_They_Match": None,
            "Error": True,
            "Error_Message": "{}".format(e)
        }


ax = number_of_doors()
if ax['Success']:
    # If success is true, extract out the values we need.
    print("Success:{}\nDo they match?{}".format(ax['Success'], ax['Do_They_Match']))
elif ax['Success'] is False:
    # check if its false, and if error is there or not.
    if ax['Error'] and len(ax['Error_Message']) != 0:
        # If error is in the dict object, then we can pull out what the error was.
        error = ax['Error_Message']
    else:
        error = None
    print("Success: {}\nError:{}".format(ax['Success'], error))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.