Skip to main content
 首页 » 编程设计

Python之为 raise exception_class(message, screen, stacktrace) 进行异常处理

2024年10月01日10yxwkf

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

我想做个异常(exception),所以当 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,即使有那个 span 标签,它也会打印“没有关于这个位置的描述”

请您参考如下方法:

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

from selenium.common.exceptions import NoSuchElementException 

而try/except部分如下:

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