2

我将如何处理 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

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

4

1 回答 1

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

像上面这样的东西应该可以工作。只要continue你得到那个错误。它将继续循环的下一次迭代,或者如果它是最后一次迭代,则跳出循环。

XML 格式不正确,无法处理。跳过它并继续下一个。

于 2013-04-09T20:19:48.333 回答