在Selenium Python3中处理自定义异常

时间:2019-04-11 09:45:40

标签: python-3.x selenium exception

我有一个脚本,该脚本可以抓取网页并与某些元素进行交互。在某些情况下,网页搜索字段会提示一些错误消息,然后我通过打印自己的错误消息而不打印回溯来进行处理(因为触发我的其他脚本的主要脚本只是查找输出,并且如果我的自定义错误消息之一被打印,则会执行操作无需追溯)。这是我的代码。 (NoSuchElementException来自selenium.common.exceptions)。第一个示例有效,它只显示正确的自定义消息,而没有堆栈跟踪:

try:
    driver.find_element_by_xpath('//a[@title="Zoom to selection"]/div').click()              
except NoSuchElementException:
    try:
        driver.find_element_by_xpath('//span[text()="No results for your search!"]')
        driver.close()
        raise CustomNoResultException
    except NoSuchElementException:
        raise CustomSomethingIsVeryWrongException

但是,这部分动作很奇怪。它首先打印我的自定义错误消息(这是我唯一想要的),然后引发NoSuchElementException的追溯,然后引发CustomResultIsNotThereException的追溯:

try:
    typeofresult = driver.find_element_by_xpath('//span[text()="' + Id + '"]/ancestor::tbody/tr[1]').text
    # before the try I switch to an iframe
    driver.switch_to.default_content()
except NoSuchElementException:
    driver.close()
    raise CustomResultIsNotThereException

我所有的自定义例外看起来都像这样:

class Custom[here the name]Exception(Exception):
def __init__(self):
    print("My custom message!")
pass

为什么我的第二个代码抛出像我的第一个示例一样被我除外和阻止的回溯?为什么以这种奇怪的顺序出现?

0 个答案:

没有答案