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"])