【问题标题】:Returned value with exception handling using Python Selenium WebDriver使用 Python Selenium WebDriver 处理异常的返回值
【发布时间】:2014-02-11 22:16:04
【问题描述】:

我想跑步

driver.find_element_by_css_selector("MY_SELECTORS").click()

在测试中,但有时该元素不存在。如果我这样做了:

return = driver.find_element_by_css_selector("MY_SELECTORS").click()

并且该元素不存在,是否会返回一个值(如异常或布尔值 FALSE)?我一直在阅读Docs » Locating Elements,但虽然它详细说明了错误类型,但不清楚是否返回值。

有人有这方面的经验吗?

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    你的语句有定位和点击两部分,会有不同的异常和返回类型。

    find_element_by_css_selector()返回webelement,可能会抛出异常,而click()为void,也可能会抛出异常。

    例如,如果您的定位器有效但没有匹配元素,则应抛出NoSuchElementException。如果找到了您的元素,但未处于可点击状态,则会引发某种类型的异常。

    # untested Python pseudo code, only provides the logic
    try:
        driver.find_element_by_css_selector("Selector doesn't exist").click()
    except ElementNotVisibleException:
        print "ElementNotVisibleException"
    except NoSuchElementException:
        print "NoSuchElementException"
    except InvalidSelectorException:
        print "InvalidSelectorException"
    except:
        print "Other exception types possible"
        raise
    

    【讨论】:

    • 谢谢,这很有帮助!对于我自己的信息,当您说“返回 webelement 并可能抛出异常”时,这无法在变量中捕获?
    • 返回类型和异常不同,为什么要这么做?这取决于你想得到什么。你可以有一个方法来返回布尔值或 webelement。
    猜你喜欢
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2020-12-09
    相关资源
    最近更新 更多