0

I'm using Selenium in Python.

In my script, I wrote this line to check if a particular element exists:

doesElementExist = driver.find_element(By.CSS_SELECTOR,'div.MediaThumbnail.Media--playButton>img').is_displayed()
print(doesElementExist)

For testing, I ran the script with a website in which I know this element do not exist. Therefore, I'm expecting a False as the returning output since the is_displayed() method returns a boolean.

However, I got an error saying this element do not exist, which stops the script from running instead of returning a false and keep the script going.

Traceback (most recent call last):

  File ~/Desktop/ImageScraping/birdsScrapeTest.py:70 in <module>
    if driver.find_element(By.CSS_SELECTOR,'div.MediaThumbnail.Media--playButton>img').is_displayed() == True:

  File /opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:1251 in find_element
    return self.execute(Command.FIND_ELEMENT, {

  File /opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:430 in execute
    self.error_handler.check_response(response)

  File /opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py:247 in check_response
    raise exception_class(message, screen, stacktrace)

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"div.MediaThumbnail.Media--playButton>img"}

Any idea why that happens?

1 Answer 1

1

That's not what the is_displayed() method does. This method will tell you whether the element is visible or not visible (hidden but in the DOM). So in order to implement the usage that you are expecting you could do instead:

try:
    doesElementExist = driver.find_element(By.CSS_SELECTOR,'div.MediaThumbnail.Media--playButton>img').is_displayed()
except NoSuchElementException:
    doesElementExists = False
    print("Element doesn't exists")

print(doesElementExist)

This logic should work whether the element is not present on the page or just hidden

Sign up to request clarification or add additional context in comments.

3 Comments

Tried and got this error:NameError: name 'NoSuchElementException' is not defined
You need to import the NoSuchElementException first like, from selenium.common.exceptions import NoSuchElementException
ok now it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.