user1592380
user1592380

Reputation: 36277

Returned value with exception handling using Python Selenium WebDriver

I want to run

driver.find_element_by_css_selector("MY_SELECTORS").click()

inside a test, but there are times that the element does not exist. if I did:

return = driver.find_element_by_css_selector("MY_SELECTORS").click()

and the element does not exist, would a value ( like an exception , or boolean FALSE) be returned? I have been reading Docs » Locating Elements, but although it details the error types, its not clear if a value is returned.

Does anyone have experience with this?

Upvotes: 2

Views: 2881

Answers (1)

Yi Zeng
Yi Zeng

Reputation: 32865

Your statement has two parts, locating and clicking, there will be different exceptions and return types.

find_element_by_css_selector() returns webelement and may throw exception, while click() is void, exception might also be thrown.

So for example, if your locator is valid but results in no matching element, NoSuchElementException should be thrown. If your element is found, but not in clickable state, some type of exception will be thrown.

# untested Python pseudo code, only provides the logic
try:
    driver.find_element_by_css_selector("Selector doesn't exist").click()
except ElementNotVisibleException:
    print "ElementNotVisibleException"
except NoSuchElementException:
    print "NoSuchElementException"
except InvalidSelectorException:
    print "InvalidSelectorException"
except:
    print "Other exception types possible"
    raise

Upvotes: 5

Related Questions