Python/Selenium试图使用;如果;未找到元素时对元素执行的语句
我试图在找不到xpath时用特定消息引发ValueErrorPython/Selenium试图使用;如果;未找到元素时对元素执行的语句,python,python-3.x,selenium,automation,Python,Python 3.x,Selenium,Automation,我试图在找不到xpath时用特定消息引发ValueError @step('Click save') def step_impl(context): click_save = context.browser.find_element_by_xpath("//button[@class='save_button']") if not click_save: raise ValueError('Save button is not found') click_save.click() 理
@step('Click save')
def step_impl(context):
click_save =
context.browser.find_element_by_xpath("//button[@class='save_button']")
if not click_save:
raise ValueError('Save button is not found')
click_save.click()
理想情况下,如果未找到保存按钮,我希望显示提升值错误。。。但是,当没有找到click_save xpath时,代码将永远不会到达“if”语句。我只会得到一个错误…诸如此类的xpath找不到或者不管它是什么
我尝试这样做是为了更具体地说,在一组测试中,您可能有类似的XPath,我想确切地知道哪一个失败了
这可能吗?由于selenium无法识别给定元素的xpath并在那里生成异常,因此出现了错误
您可以做的是,将代码保存在try/catch块中,然后执行代码。Selenium无法找到元素并抛出错误。您可以检查元素的长度计数,如果它为零,则会引发错误 请尝试下面的代码
if len(browser.find_elements_by_xpath("//button[@class='save_button']"))==0:
raise ValueError('Save button is not found')
else:
click_save = browser.find_element_by_xpath("//button[@class='save_button']")
click_save.click()
我不会不必要地生成错误,而是获取匹配元素的计数并比较len,如下所示
@step('Click save')
def step_impl(context):
numberOFSaveElems = len(context.browser.find_elements_by_xpath("//button[@class='save_button']"))
if numberOfSaveElems==0:
raise ValueError('Save button is not found')
click_save.click()