0

I have a very simple code where I am looking for a class and when that class doesn't exist I want to catch that and update a status in my CSV. I am implementing this like:

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

invalid = browser.find_element_by_class_name('_3lLzD')
try:
    Update status
except NoSuchElementException as e:
    Update Status

It still throws me the error:

Traceback (most recent call last):
  File "C:/Users/Krenovate/Desktop/automate/automate/automate.py", line 35, in <module>
    invalid = browser.find_element_by_class_name('_3lLzD')
  File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: ._3lLzD

What am I doing wrong

Bhanu
  • 351
  • 2
  • 15

1 Answers1

1

Per the documentation, the locator function is designed to throw an exception if it is not found. Therefore, the exception that you get is well within the expected behavior.

If you are unsure of the presence of the element, the easiest way is to place it within a try block

try:
    invalid = browser.find_element_by_class_name('_3lLzD')
    Update status
except NoSuchElementException as e:
    Update Status

or use explicit waits with a timeout.

kerwei
  • 1,822
  • 1
  • 13
  • 22