我試圖從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
它會打印「沒有這個位置描述」太甚至有跨度標籤