Python除特定键错误外

时间:2018-02-19 21:04:23

标签: python xml exception-handling beautifulsoup keyerror

我正在使用Beautiful Soup解析XML文件。有时我的条目缺少一个或多个我正在解析的键。我想设置异常来处理这个问题。我的代码看起来像这样:

for entry in soup.findAll('entry_name'):
    try:
        entry_dict = dict(entry.attrs)
        x = entry_dict["x"]
        y = entry_dict["y"]
        z = entry_dict["z"]

        d[x] = [y, z]
    except KeyError: 
        y = "0"
        d[x] = [y, z]

问题是我可以根据条目丢失“y”,“z”或“y和z”两者。有没有办法处理特定的KeyErrors?像这样:

except KeyError "y":
except KeyError "z":
except KeyError "y","z":

3 个答案:

答案 0 :(得分:0)

您可以检查异常参数:

a = {}
try:
    a['a']
except KeyError as e:
    # handle key errors you want
    if e.args[0] == 'a':
        pass
    # reraise the exception if not handled
    else:
        raise

答案 1 :(得分:0)

我个人不会在这里使用try / except而是使用检测方法而不是处理方法。

if not 'y'  in entry_dict.keys() and not 'z' in entry_dict.keys():
  # handle y and z missing
elif not 'y' in entry_dict.keys():
  # handle missing y
elif not 'z' in entry_dict.keys():
  # handle missing z

答案 2 :(得分:0)

Paweł Kordowski答案略有不同:

a = {}
try:
    a['a']
except KeyError as e:
    # 2 other ways to check what the missing key was
    if 'a' in e.args:
        pass
    if 'a' in e:
        pass
    # reraise the exception if not handled
    else:
        raise