我正在使用xmltodict来解析xml。
如果我们解析无效的xml,它会抛出一个ExpatError。
我怎么抓到这个?下面是我在ipython shell中尝试过的内容
>>> 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'发布于 2014-08-07 13:46:28
您需要从ExpatError中导入xml.parsers.expact。
from xml.parsers.expat import ExpatError发布于 2014-08-07 13:49:50
在xmltodict模块本身中找到它,因此不需要将它与xml模块单独导入。
>>> try:
... xml_dict = xmltodict.parse(xml_data)
... except xmltodict.expat.ExpatError:
... print "that's right"
...
that's righthttps://stackoverflow.com/questions/25184153
复制相似问题