未封闭的XML令牌

时间:2013-04-09 20:17:36

标签: python xml

如何在Python 2.6中处理此错误?

Traceback (most recent call last):
  File "./fetch_xml_collect.py", line 32, in <module>
    tree=ET.parse(response)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 862, in parse
    tree.parse(source, parser)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 587, in parse
    self._root = parser.close()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 1254, in close
    self._parser.Parse("", 1) # end of data
xml.parsers.expat.ExpatError: unclosed token: line 56, column 1

正在实施的当前代码:

while urlget==1:
        try:
                response = urllib.urlopen(rep)
        except IOError:
                print("reason")
        else:
                try:
                        tree=ET.parse(response)
                except IOError:
                        print("XML Parse Error\n")
                else:
                        root=tree.getroot()
                        print root[0].text
                        powerlist=tree.findall('meter/power')
                        print powerlist[0].tag,powerlist[0].text

问题是:如何处理给定代码中的上述错误?

1 个答案:

答案 0 :(得分:6)

try:
   #Some code
   ...
except xml.parsers.expat.ExpatError, ex:
   print ex
   continue

像上面这样的东西应该有效。如果您收到错误,只需continue。它将继续循环的下一次迭代,或者如果它是最后一次迭代,则突破循环。

XML格式错误,无法处理。跳过它然后继续下一个。