我正在使用xmltodict解析XML。
如果我们分析无效的XML,它将抛出一个ExpatError
我怎么能抓住这个?这是我在ipython壳里试过的

>>> import xmltodict
>>> xml_data = """<?xml version="1.0" encoding="UTF-8" ?>
...     <Website>"""

>>> xml_dict = xmltodict.parse(xml_data)
ExpatError: no element found

>>> try:
...     xml_dict = xmltodict.parse(xml_data)
... except ExpatError:
...     print "that's right"
NameError: name 'ExpatError' is not defined

>>> try:
...     xml_dict = xmltodict.parse(xml_data)
... except xmltodict.ExpatError:
...     print "that's right"
AttributeError: 'module' object has no attribute 'ExpatError'

最佳答案

您需要从ExpatError导入xml.parsers.expact

from xml.parsers.expat import ExpatError

07-27 18:24