2017-01-17 60 views
0

我使用Python的Selenium webdriver打印內容的一個元素,但如果它不存在於頁面上,它會破壞我的代碼並返回一個異常錯誤。Selenium Webdriver NoSuchElementException

print (driver.find_element_by_id("TotalCost").text) 

NoSuchElementException: Message: no such element: Unable to locate element 
{"method":"id","selector":"TotalCost"} 

我可以做些什麼來解決這個錯誤?

+0

你能趕上('除了NoSuchElementException異常如前:')這個異常。 –

+0

我在打印聲明後的位置? (除了NoSuchElementException除外:) – 7O07Y7

+1

閱讀關於[例外](https://docs.python.org/3.5/tutorial/errors.html) –

回答

1

趕上在try...except塊除外:

from selenium.common.exceptions import NoSuchElementException 

try: 
    print(driver.find_element_by_id("TotalCost").text) 
except NoSuchElementException: 
    print("Element not found") # or whatever you want to print, or nothing 

也可以爲清楚起見,做這種方式:

try: 
    elem = driver.find_element_by_id("TotalCost") 
except NoSuchElementException: 
    pass 
else: 
    print(elem.text) 
+0

謝謝你明確我沒有意識到我需要'導入NoSuchElementException'。這就是爲什麼它不工作之前! – 7O07Y7

+0

很高興解決。請參閱[如何接受答案?](http://meta.stackexchange.com/a/5235/193893) – aneroid