返回值,并使用Python Selenium WebDri进行异常处理

2024-10-05 14:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想跑

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

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

^{pr2}$

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

有人有这方面的经验吗?在


Tags: false元素docsbymydriverelementfind
1条回答
网友
1楼 · 发布于 2024-10-05 14:21:46

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

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

相关问题 更多 >