首页 > 解决方案 > 在 Python 中执行延迟执行并获取异常的默认值

问题描述

我正在解析 HTML 并且在文件中有很多可选的属性,如果在我阅读它们时引发异常,我会使用一些默认值。有没有办法准备一个通用函数来尝试检索属性并在异常时返回默认值?目前,我有这样的东西,但它非常难看。

        try:
            title = soup.find('h1').text
        except:
            title = "b/d"
        try:
            location = soup.find('a', attrs={'href': '#map'}).text
        except:
            location = "none"
        try:
            downside= soup.find('strong', attrs={'aria-label': 'downside'}).text
        except:
            downside = "0"
        try:
            incremental = soup.find('div', attrs={'aria-label': 'incremental'}).contents[3].text
        except:
            incremental = "1"
        try:
            difference = soup.find('div', attrs={'aria-label': 'difference'}).contents[1].text
        except:
            difference = "2"
        try:
            part = soup.find('div', attrs={'aria-label': 'part'}).contents[1].text
        except:
            part = "3"

标签: pythonexceptiondefault

解决方案


  • 不要捕获裸异常。

实现泛型函数的一种直接方法是

def get_attribute_text(soup, element, attrs, default_value, contents_index=None):
    try:
        if contents_index:
            return soup.find(element, attrs=attrs).contents[contents_index].text
        return soup.find(element, attrs=attrs).text
    except AttributeError:
        return default_value

并使用如下:

title = get_attribute_text(soup, 'h1', {}, 'b/d')
location = get_attribute_text(soup, 'a', {'href': '#map'}, 'none')
...
incremental = get_attribute_text(soup, 'div', {'aria-label': 'incremental'}, '1', 3)
...

推荐阅读