XML模块在Python中解析2.7.6和2.7.3之间的差异

时间:2014-03-09 02:23:02

标签: python xml python-2.7

我正在使用这个tutorial来讨论Python的一些概念,但是,我试图在2.76中使用这行代码遇到了这个问题。 Dave在monitor.py文件中的视频的53分钟部分使用2.73。

我正在使用这行代码来尝试修复错误......

from xml.etree.ElementTree import parse

反对

import xml.etree.ElementTree import parse 

(这是python 2.7.3中视频中使用的内容)

但是当我使用它时它不起作用。我反而得到了这个错误。

   PS C:\python27> python monitor.py
   Traceback (most recent call last):
     File "monitor.py", line 28, in <module>
        monitor()
      File "monitor.py", line 15, in monitor
       doc = parse(u)
      File "C:\Python27\lib\xml\etree\ElementTree.py", line 1182, in parse
       tree.parse(source, parser)
      File "C:\Python27\lib\xml\etree\ElementTree.py", line 656, in parse
       parser.feed(data)
     File "C:\Python27\lib\xml\etree\ElementTree.py", line 1642, in feed
        self._raiseerror(v)
      File "C:\Python27\lib\xml\etree\ElementTree.py", line 1506, in _raiseerror
        raise err
    xml.etree.ElementTree.ParseError: undefined entity &nbsp;: line 50, column 47

我应该编写哪些代码代码?为什么?我试过'as'和'import'

以下是我正在使用的代码。

#monitor.py
import urllib
from xml.etree.ElementTree import parse

candidates = ['4131','4163','4132']
daves_latitude = 41.980262


def distance(lat1, lat2):
    'Return distance in miles between two lats'
    return 69*(lat1 - lat2)

def monitor():
    u = urllib.urlopen('http://ctabustracker.com/bustime/mapgetBusesForRoute.jsp?route=22')
    doc = parse(u)
    for bus in doc.findall('bus'):
        busid = bus.findtext('id')
        if busid in candidates:
            lat = float(bus.findtext('lat'))
            dis = distance(lat, daves_latitude)
            print busid, dis, 'miles'
        print '-'*10


import time

while True:
    monitor()
    time.sleep(60)

1 个答案:

答案 0 :(得分:0)

#XXX INCORRECT, DO NOT USE IT
import xml.etree.ElementTree import parse 

错误xml.etree.ElementTree.ParseError: undefined entity &nbsp与您以任何方式导入ElementTree模块的方式无关。 Python 2.7.6和2.7.3中的行为相同。

解释此问题的

@karthikr linked to the question in the comments:默认情况下未为xml定义&nbsp;,请参阅Parse XML with (X)HTML entities