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+"/")
try:
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:
try:
# do stuff
except NoSuchElementException as e:
print e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With