【问题标题】:Python - Make exception handling for raise exception_class(message, screen, stacktrace)Python - 为 raise exception_class(消息、屏幕、堆栈跟踪)进行异常处理
【发布时间】: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


    【解决方案1】:

    只需将其添加到您的导入部分:

    from selenium.common.exceptions import NoSuchElementException
    

    而try/except部分如下:

    try:
        # do stuff
    
    except NoSuchElementException as e:
        print e
    

    【讨论】:

      【解决方案2】:

      除了使用

      except Exception: print "There's no description about this location"

      【讨论】:

        猜你喜欢
        • 2021-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-21
        • 2022-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多