2013-04-09 49 views
2

我將如何處理Python 2.6中的這個錯誤?未封閉的XML令牌

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 

的問題是:我怎麼會在給定的代碼處理上述錯誤?

+0

嘗試使用'lxml.html'解析它 – root 2013-04-09 20:25:08

回答

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

像上面這樣的東西應該工作。只要continue,如果你得到這個錯誤。它將繼續進行循環的下一次迭代,或者如果它是最後一次迭代,則跳出循環。

XML形式不正確,無法處理。只需跳過它並繼續下一個。

+0

感謝您的幫助 – user2263305 2013-04-09 21:36:37

+0

如果它有幫助,您可以請它upvote嗎? – cxdf 2013-04-09 22:12:41

+0

thans您的幫助。當然。我想這樣做,我只是登記帳戶。沒有足夠的聲譽。 – user2263305 2013-04-15 14:41:15