Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-为raise exception_类(消息、屏幕、堆栈跟踪)进行异常处理_Python_Selenium_Exception_Exception Handling - Fatal编程技术网

Python-为raise exception_类(消息、屏幕、堆栈跟踪)进行异常处理

Python-为raise exception_类(消息、屏幕、堆栈跟踪)进行异常处理,python,selenium,exception,exception-handling,Python,Selenium,Exception,Exception Handling,我正在尝试使用python中的selenium从chromedriver中的标记获取文本。我的代码运行正常,但当没有应该获取的标记时,脚本会引发错误并停止。错误: raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":

我正在尝试使用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"

我不知道应该使用什么异常来处理那个错误。如果我只使用
,除了
,它也会打印“没有关于此位置的说明”,即使有span标记

只需将此添加到导入部分:

from selenium.common.exceptions import NoSuchElementException
而try/except部分如下所示:

try:
    # do stuff

except NoSuchElementException as e:
    print e
除用途外

例外情况除外:
打印“没有关于此位置的说明”