2017-02-14 30 views
1

我試圖從python中的seroium在chromedriver中的標記中獲取文本。我的代碼正確運行,但是當沒有應該得到的標記時,腳本會發出錯誤並停止。錯誤:Python - 爲引發異常處理exception_class(消息,屏幕,堆棧跟蹤)

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" 

我不知道我應該用什麼異常來處理這個錯誤。如果我只使用except它會打印「沒有這個位置描述」太甚至有跨度標籤

回答

0

只需添加到您的導入部分:

from selenium.common.exceptions import NoSuchElementException 

而且嘗試/除部分如下:

try: 
    # do stuff 

except NoSuchElementException as e: 
    print e 
0

以外使用

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