【发布时间】:2017-02-14 04:51:23
【问题描述】:
我正在尝试使用 python 中的 selenium 从 chromedriver 中的标签中获取文本。我的代码运行正确,但是当没有我应该得到的标签时,脚本会引发错误并停止。错误:
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)
我想例外,所以当 selenium 找不到标签时,它会打印一条消息而不是停止脚本。我的代码:
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"
我不知道应该使用什么异常来处理该错误。如果我只使用except,即使有跨度标签,它也会打印“没有关于此位置的描述”
【问题讨论】:
标签: python selenium exception exception-handling