Search code examples
pythonxmlexceptionbeautifulsoupkeyerror

Python Except Specific Key Error


I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this:

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]

The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to handle specific KeyErrors? Something like this:

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

Solution

  • Personally I wouldn't use a try/except here and instead go for the detection approach instead of the handling approach.

    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