【问题标题】:Alternative to Consecutive Try/Except Blocks替代连续尝试/排除块
【发布时间】:2018-12-06 22:42:52
【问题描述】:

我对 Python 还很陌生,所以我想知道是否有比运行大量连续的 try/except 块更简洁的替代方法,如下所示?

try:
    project_type = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-type")]').text
except Exception:
    project_type = 'Error'
try:
    title = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-title")]').text
except Exception:
    title = 'Error'
try:
    description = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-description")]').text
except Exception:
    description = 'Error'
try:
    category = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-category")]').text
except Exception:
    category = 'Error'
...

正如this threadthis thread, 中所建议的那样,我想我可以创建变量名和查询列表,然后使用for 循环为每个容器项构造一个字典,但真的没有其他选择哪些可能更具可读性?

【问题讨论】:

    标签: python error-handling try-catch


    【解决方案1】:

    你的代码有很多混乱的原因是因为你有重复的代码。您连续四次表达相同的想法(查找一个值,如果失败则设置默认值),这自然意味着您也必须编写四次相同的支持代码。

    循环是修复重复代码的好方法 - 因此使用名称列表查找并创建值字典是您的完美解决方案。这使您可以编写逻辑一次,然后多次使用它。

    (另外:您的代码重复导致了一个错误!前两个 try-except 块将 'Error' 值分配给 description 而不是适当的变量。重复代码可能会咬人!)

    【讨论】:

    • 我想知道是否有替代使用某种循环来构造对象的方法。 为什么说前两个try-except 块分配了抛出异常?!?!
    • 我的意思是您最终将 description 的值设置为 'Error',即使它实际上是您未能为其查找值的 project_type 变量。
    • 哦,我明白你现在指的是什么,错字了。该死的复制粘贴
    【解决方案2】:

    您可以将调用抽象为find_element_by_xpath;这避免了代码重复,并使您的代码更具可读性:

    def _find_element_by_xpath(body, xpath)
        try:
            return body.find_element_by_xpath(xpath).text
        except Exception:   # <-- Be specific about the Exception to catch
            return 'Error'
    
    def get_a_specific_xpath(element):
        return f'./div[contains(@class, "discoverableCard-{element}")]'
    

    那么你的代码就变成了:

    project_type = _find_element_by_xpath(body, get_a_specific_xpath('project_type'))
    title = _find_element_by_xpath(body, get_a_specific_xpath('title'))
    description = _find_element_by_xpath(body, get_a_specific_xpath('description'))
    category = _find_element_by_xpath(body, get_a_specific_xpath('category'))
    ...
    

    【讨论】:

    • tbh,我对 python(和 selenium)太陌生了,我不确定我在寻找哪个异常,哈哈。我知道如果你输入了错误的Exception,如果抛出不同的异常,它会破坏脚本。 **哦,等等,value = xpathvalue 不是也必须是参数吗?
    • @Anthony,我现在连续拒绝了您的三个破坏代码的编辑;你为什么不告诉我你想要什么,我会看看如何适应它。
    • 大声笑你认为.txt属于哪个属性?不是所有的 xpath 路径都是'./div[contains(@class, "discoverableCard-{element}")]' 所以它必须能够接受任何路径...
    • 我理解 - 您可以将路径构造抽象为几个不同的函数,这些函数将返回所需的特定路径......如果需要,您可以进一步抽象路径构造以接受参数。这里的关键,与您提出问题的动机相对应,是保持主要代码简洁明了。
    • 嗯?正如你所说,我不想抽象路径。 另外,它是 .text,而不是 .txt 但既然你否认我的所有编辑......这应该在代码的其他地方处理,但如果你真的没关系把它留在你的答案中
    猜你喜欢
    • 2015-10-15
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2013-05-28
    • 1970-01-01
    • 2014-12-31
    相关资源
    最近更新 更多