Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the try/except with Selenium Webdriver when having Exceptions on Python

I'm trying the use a try/except statement to findout if an element exists in the WebDrive or not, if so then run a specific code line,

try:
    WebDriver.find_element_by_css_selector('div[class="..."')
except NoSuchElement:
    ActionToRunInCaseNoSuchElementTrue
else:
    ActionToRunInCaseNoSuchElementFalse

but running this code gives an error:

  • NameError: name 'NoSuchElement' is not defined

how should the Exception be defined? Is there any shorter/easier way to check if an element does exist in a web page and run a command if so and another if not?

like image 926
Anas Bouayed Avatar asked May 11 '17 11:05

Anas Bouayed


2 Answers

To be able to use required exception you have to import it first with correct name (NoSuchElement -> NoSuchElementException):

from selenium.common.exceptions import NoSuchElementException

try:
    WebDriver.find_element_by_css_selector('div[class="..."')
except NoSuchElementException:
    ActionToRunInCaseNoSuchElementTrue
like image 80
Andersson Avatar answered Sep 29 '22 11:09

Andersson


Instead of using try except you can use find_elements and check if the returned list has any elements

elements = WebDriver.find_elements_by_css_selector('div[class="..."')
if not elements:
    ActionToRunInCaseNoSuchElementTrue
else:
    ActionToRunInCaseNoSuchElementFalse
    # the element is in elements[0]
like image 43
Guy Avatar answered Sep 29 '22 12:09

Guy