2012-05-30 148 views
1

我的XML代码的网络弄来了看起来像这样XML在python解析

<?xml version='1.0' ?><liverequestresponse><liverequesttime>180</liverequesttime><livemessage></livemessage></liverequestresponse> 

和我的Python minidom命名代码

import urllib, urllib2, time 
from xml.dom.minidom import parse 
response = urllib2.urlopen(req) 
the_page = response.read() 
#print the_page 
dom = parse(response) 
name = dom.getElementsByTagNameNS('liverequestresponse') 
print name[0].nodeValue 

给出了一些错误

print the_page 

工作正常

或者如果他们是其他人这比minidom命名更好的库,PLZ告诉我.. 我宁愿它是预安装在Linux

UPDATE

错误

Traceback (most recent call last): 
    File "logout.py", line 18, in <module> 
    dom = parse(response) 
    File "/usr/lib64/python2.7/xml/dom/minidom.py", line 1920, in parse 
    return expatbuilder.parse(file) 
    File "/usr/lib64/python2.7/xml/dom/expatbuilder.py", line 928, in parse 
    result = builder.parseFile(file) 
    File "/usr/lib64/python2.7/xml/dom/expatbuilder.py", line 211, in parseFile 
    parser.Parse("", True) 
xml.parsers.expat.ExpatError: no element found: line 1, column 0 
+0

...并且错误是? – Hamish

+0

更新PLZ检查 – pahnin

回答

3

如果使用response.read的一个在parse(response)之前,您已经阅读了回复的内容。第二次调用response.readparse正在执行)将导致一个空字符串。

最简单的解决方案是放弃第一个response.read调用。但是,如果你真的需要出于某种原因响应字符串,你可以尝试:

import urllib, urllib2, time 
import StringIO 
from xml.dom.minidom import parse 
response = urllib2.urlopen(req) 
the_page = response.read() 
#print the_page 
dom = parse(StringIO.StringIO(the_page)) 
name = dom.getElementsByTagName('liverequesttime') 
text = name[0].firstChild 
print text.nodeValue 
+0

它打印没有!,我也尝试删除response.read太..它不那么重要,所以我评论它,并运行脚本输出没有 – pahnin

+0

它打印'None',因为'liverequestresponse'节点没有值。它只包含一个子节点,它包含一个具有值的文本节点。 'minidom'不是用户最友好的XML解析库。 'lxml'更好,或者'xml.etree'更好。 – mata

+0

这工作,我尝试与'childnode',但它没有奏效!谢谢 – pahnin

1

lxml的一种方法,它是在Python是非常使用的最近以非常优异的成绩,性能解析XML:

import urllib2 
from lxml import etree 

with urllib2.urlopen(req) as f: 
    xml = etree.parse(f) 

xml.find('.//liverequesttime').text 

最后一行的输出为:180

+0

必须安装lxml有没有比minidom更好的内置库? – pahnin

+0

lxml需要安装,但它已经预先打包在很多linux发行版上,尽管你总是可以用'easy_install'安装它。 –

+0

我不想冒险写我为简约linux写的http登录客户机,我可能必须在Arch linux核心上使用它 – pahnin