Selenium围绕“ TimeoutException”的工作没有定义?

时间:2019-10-10 17:29:13

标签: python selenium

我想解决 Python Selenium中的 TimeOutException。

发生这种情况:

1.) Open Browser, Call URL
2.) Trying to find Element
2.1) Works sometimes
2.2) Works not sometimes and throws TimeoutException
3.) Should look for other elements

3.)中遇到异常并且尝试/捕获不起作用后,我再也无法到达步骤2.2)

在步骤3.)之后,还有许多其他步骤。我如何让程序在此超时时间内流动。元素不存在时正在超时。

代码

    def getByClass(InputElement, driver):
        getByClass = WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, InputElement)))
        return getByClass

    try:
        element = Dom.getByClass('test-class', driver).text
    except TimeoutException:
        element = 'element not found'
    print(element)

结果

    except TimeoutException:
    NameError: name 'TimeoutException' is not defined

2 个答案:

答案 0 :(得分:1)

我无法从示例中看到您的导入语句,因此请确保您拥有

from selenium.common.exceptions import TimeoutException  在.py文件的顶部。

答案 1 :(得分:1)

从硒异常中导入TimeoutException

from selenium.common.exceptions import TimeoutException

将函数放入try块本身内:

try:
    getByClass = WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, InputElement)))
    element = Dom.getByClass('test-class', driver).text
except TimeoutException:
    element = 'element not found'
print(element)