Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm trying to get text from a tag in chromedriver with selenium in python. My code run correctly but when there's no tag that should I get, the script raise an error and stop. The error:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//span[@class="section-facts-description-text"]"}
(Session info: chrome=56.0.2924.87)
(Driver info: chromedriver=2.27.440174(e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.14393 x86_64)
I want to make exception, so when selenium can't find the tag, it will print a message and not stop the script. My code:
import os
import sys
from selenium import webdriver
def findLocation(location):
browser = webdriver.Chrome()
print "please wait, I'll show you where "+location+" is"
browser.get("https://www.google.co.id/maps/place/"+location+"/")
elem = browser.find_element_by_xpath('//span[@class="section-facts-description-text"]')
desc = elem.text
print str(desc)
except:
print "There's no description about this location"
I don't know what exception I should use to handle just that error. If I use just except
it will print "There's no description about this location" too even there's that span tag
Just add this to your import section:
from selenium.common.exceptions import NoSuchElementException
And the try/except part is as follows:
# do stuff
except NoSuchElementException as e:
print e
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.