Selenium Webdriver NoSuchElementException

时间:2017-01-17 22:01:27

标签: python selenium-webdriver phantomjs

我使用Selenium webdriver和Python打印内容元素,但如果页面上不存在,则会破坏我的代码并返回异常错误。

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

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

我该怎么做才能解决此错误?

1 个答案:

答案 0 :(得分: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)