2016-02-26 52 views
0

我正在使用Python Selenium從列表中打開URL並找到某個元素。像這樣......Python Selenium在找不到元素時崩潰

driver.get('http://www.example.com.com/') 
inputElement = driver.find_element_by_id("my-field") 

如果該元素存在,那麼一切工作正常,但如果元素不能被隨後找到了腳本CS出錯崩潰......

Unable to locate element: 

這是正確的行爲,有沒有辦法處理這個問題而不是崩潰?

+0

您可能要添加[等待](http://selenium-python.readthedocs.org/waits.html)真的確認該元素不存在。 – JRodDynamite

回答

1

是的。從文檔:

... 有了這個戰略,id爲第一要素屬性相匹配的位置將被返回的值 。如果沒有元素具有匹配的 id屬性,則會引發NoSuchElementException。

而且當然可以捕捉異常(就像在另一個答案中提到的那樣)。

你可以在這裏找到文檔: http://selenium-python.readthedocs.org/locating-elements.html#locating-by-id

6

這是正確的行爲。

您可以捕獲該異常,就像你可以在任何例外:

from selenium.common.exceptions import NoSuchElementException 
... 
try: 
    driver.get('http://www.example.com.com/') 
    inputElement = driver.find_element_by_id("my-field") 
except NoSuchElementException: 
    print("couldn't find the element")