我试图通过python中的selenium从chromedriver中的标签中获取文本。我的代码运行正常但是如果没有我应该得到的标记,脚本会引发错误并停止。错误:
chars.Count
我想要例外,所以当selenium找不到标签时,它会打印一条消息而不会停止脚本。我的代码:
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)
我不知道应该用什么异常来处理这个错误。如果我只使用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"
,则会打印"此处没有关于此位置的说明"甚至还有那些跨越标签的
答案 0 :(得分:2)
只需将其添加到导入部分:
from selenium.common.exceptions import NoSuchElementException
try / except部分如下:
try:
# do stuff
except NoSuchElementException as e:
print e
答案 1 :(得分:0)
除了使用
except Exception:
print "There's no description about this location"