Python
WebDriverException
是一個基礎 Selenium-WebDriver
異常,可用於捕獲所有其他 Selenium-WebDriver
異常
為了能夠捕獲異常,應首先匯入:
from selenium.common.exceptions import WebDriverException as WDE
然後:
try:
element = driver.find_element_by_id('ID')
except WDE:
print("Not able to find element")
以同樣的方式,你可以匯入其他更具體的例外:
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import NoAlertPresentException
...
如果只想提取異常訊息:
from selenium.common.exceptions import UnexpectedAlertPresentException
try:
driver.find_element_by_tag_name('a').click()
except UnexpectedAlertPresentException as e:
print(e.__dict__["msg"])