【问题标题】:Exception is thrown even though there is a try...except block [duplicate]即使有尝试,也会引发异常...except块[重复]
【发布时间】:2021-08-23 20:04:26
【问题描述】:

我有这个尝试...除了块:

try:
    browser.find_element('xpath', '/html/body/ul').click()
    wait = WebDriverWait(browser, 10)
    wait.until(EC.visibility_of_element_located(('xpath', '/html/body/div[1]/div[3]/span')))
    return ' '.join(browser.find_element('id', 'response').text.split('\n')[0].split()[:-1])

except ElementNotInteractableException or NoSuchElementException or TimeoutException:
    return 'No result'

我仍然得到这个异常:

    wait = WebDriverWait(browser, 10)
File "C:\...\selenium\webdriver\support\wait.py", line 87, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

我试过单独处理这个异常,但没有奏效。所以我不明白我应该如何处理它,因为代码应该忽略超时,因为它只是意味着找不到元素(预计在大约 10% 的时间内)。

【问题讨论】:

    标签: python selenium webdriverwait


    【解决方案1】:

    except 子句捕获单个异常或多个异常,具体取决于关键字 except 后面的表达式的计算结果。

    1. 如果它评估为单个异常类,它将捕获该类型的异常。

    2. 如果计算结果为元组,它将捕获元组中包含的任何类型的异常。

    表达式 ElementNotInteractableException or NoSuchElementException or TimeoutException 计算结果为单一类型 ElementNotInteractableException,而不是包含三个异常类的元组。

    你想要一个显式的元组:

    except (ElementNotInteractableException, NoSuchElementException, TimeoutException):
        ...
    

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多