Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python Selenium WebDriver进行异常处理的返回值_Python_Selenium_Selenium Webdriver - Fatal编程技术网

使用Python Selenium WebDriver进行异常处理的返回值

使用Python Selenium WebDriver进行异常处理的返回值,python,selenium,selenium-webdriver,Python,Selenium,Selenium Webdriver,我想跑步 driver.find_element_by_css_selector("MY_SELECTORS").click() 在测试内部,但有时该元素不存在。如果我这样做了: return = driver.find_element_by_css_selector("MY_SELECTORS").click() 如果元素不存在,是否会返回值(如异常或布尔值FALSE)?我一直在阅读,但尽管它详细说明了错误类型,但不清楚是否返回了值 有人对此有经验吗?您的语句有两个部分,定位和单击,将出现

我想跑步

driver.find_element_by_css_selector("MY_SELECTORS").click()
在测试内部,但有时该元素不存在。如果我这样做了:

return = driver.find_element_by_css_selector("MY_SELECTORS").click()
如果元素不存在,是否会返回值(如异常或布尔值FALSE)?我一直在阅读,但尽管它详细说明了错误类型,但不清楚是否返回了值


有人对此有经验吗?

您的语句有两个部分,定位和单击,将出现不同的异常和返回类型

find\u element\u by\u css\u selector()
返回webelement并可能引发异常,而
click()
无效,也可能引发异常

# 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
例如,如果您的定位器是有效的,但是没有匹配的元素,那么应该抛出
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

谢谢,这很有帮助!关于我自己的信息,当你说“returns webelement and may throw exception”时,这不能在变量中捕获?返回类型和异常不同,为什么要这样做?这取决于你想要什么。您可以使用一个方法返回boolean或webelement。