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?
CodePudding user response:
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