Python:如何处理try / except更快?

时间:2017-04-24 18:29:31

标签: python python-2.7

目前在我的项目中,我正在处理异常:

try:
   …
   # Run code 1
except:
   …
   # Run code 2

但是当我的except处理错误时 - 错误是常见的并且是预期的,它需要一段时间来识别错误以处理异常并执行code 2。 有没有办法让程序更快地识别错误以更快地处理异常?

提前感谢您,一定要投票/接受回答

1 个答案:

答案 0 :(得分:2)

很明显,找到option by text的代码是关于代码的缓慢部分。这并不太令人惊讶,因为它必须查看整个文档才能得到结果,查询文本中没有单个元素。

所以减慢代码速度的原因是你必须两次查看文档才能找到带有任何文本的选项。您可以尝试通过查找所有选项元素然后自己查找这些文本来查看文档一次。我不知道这个库,但我想你可以使用find_by_tag。这应该为您提供list可以迭代,然后您可以查看每个元素的text以查看'red''blue'

为了确保您使用'red'文字'blue'优先选项,您需要查看列表中的所有元素。您不能因为找到任何这些颜色而停止,否则可能会找到蓝色的颜色,尽管文档后面会出现红色。所以你需要记住蓝色匹配,直到你找到一个红色元素(在这种情况下一个获胜),或者你到达文档的末尾。

这可能看起来像这样(完全推测和未经测试):

def getRedOrBlueOption(browser):
    blueOption = None
    for option in browser.find_by_tag('option'):
        # if we find a red one, we’re already done
        if option.text() == 'red':
            return option

        # if we find a blue one, and we didn’t already find another one,
        # remember that for later.
        elif option.text() == 'blue' and not blueOption:
            blueOption = option

        # otherwise, just keep looking

    # After looking at the last option, if we’re here, we didn’t find
    # a red option. However, we could have found a blue one. If that’s
    # the case, `blueOption` will contain that option. If we didn’t find
    # either of those options, `blueOption` will be still `None` which
    # we could either return to signalize that we didn’t find anything, or
    # throw an exception

    # if blueOption is None:
    #     raise ValueError('Red or blue option not found')

    return blueOption
相关问题