使用Python从URL获取XML字段

时间:2012-10-18 15:37:57

标签: python xml url xml-parsing python-2.7

我正在尝试从URL中的XML文件中获取特定字段的信息。在我开始尝试之前,我得到了这些奇怪的错误。这是我的代码:

url1 = 'http://www.dac.unicamp.br/sistemas/horarios/grad/G5A0/indiceP.htm'
data1 = urllib.urlopen(url1)
xml1 = minidom.parse(data1)

我收到此错误:

File "C:\Users\Administrator\Desktop\teste.py", line 15, in <module>
    xml1 = minidom.parse(data1)
  File "C:\Python27\lib\xml\dom\minidom.py", line 1920, in parse
    return expatbuilder.parse(file)
  File "C:\Python27\lib\xml\dom\expatbuilder.py", line 928, in parse
    result = builder.parseFile(file)
  File "C:\Python27\lib\xml\dom\expatbuilder.py", line 207, in parseFile
    parser.Parse(buffer, 0)
ExpatError: not well-formed (invalid token): line 4, column 22

我做错了什么吗?我从教程中复制了这些函数,看起来它应该正常工作..

1 个答案:

答案 0 :(得分:1)

使用lxml.html,它会更好地处理无效的xhtml。

import lxml.html as lh
In [24]: xml1=lh.parse('http://www.dac.unicamp.br/sistemas/horarios/grad/G5A0/indiceP.htm')