Python 如何用ElementTree解析收缩web xml
我正在尝试使用收缩web服务来创建网站缩略图。他们有一个返回XML的API,告诉您是否可以创建站点缩略图。我试图使用ElementTree解析xml,但不确定如何获取所需的信息。以下是XML响应的一个示例:Python 如何用ElementTree解析收缩web xml,python,elementtree,Python,Elementtree,我正在尝试使用收缩web服务来创建网站缩略图。他们有一个返回XML的API,告诉您是否可以创建站点缩略图。我试图使用ElementTree解析xml,但不确定如何获取所需的信息。以下是XML响应的一个示例: <?xml version="1.0" encoding="UTF-8"?> <stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd"> <st
<?xml version="1.0" encoding="UTF-8"?>
<stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd">
<stw:Response>
<stw:ThumbnailResult>
<stw:Thumbnail Exists="false"></stw:Thumbnail>
<stw:Thumbnail Verified="false">fix_and_retry</stw:Thumbnail>
</stw:ThumbnailResult>
<stw:ResponseStatus>
<stw:StatusCode>Blank Detected</stw:StatusCode>
</stw:ResponseStatus>
<stw:ResponseTimestamp>
<stw:StatusCode></stw:StatusCode>
</stw:ResponseTimestamp>
<stw:ResponseCode>
<stw:StatusCode></stw:StatusCode>
</stw:ResponseCode>
<stw:CategoryCode>
<stw:StatusCode>none</stw:StatusCode>
</stw:CategoryCode>
<stw:Quota_Remaining>
<stw:StatusCode>1</stw:StatusCode>
</stw:Quota_Remaining>
</stw:Response>
</stw:ThumbnailResponse>
修复并重试
检测到空白
没有一个
1.
我需要得到“stw:StatusCode”。如果我试图在“stw:StatusCode”上查找,我会得到一个“预期路径分隔符”语法错误。有没有办法只获取状态代码?Grrr名称空间…请尝试以下操作:
STW_PREFIX = "{http://www.shrinktheweb.com/doc/stwresponse.xsd}"
(参见示例XML的第2行)
然后,当您需要类似于stw:StatusCode
的标记时,请使用stw\u前缀+“StatusCode”
更新:XML响应不是最出色的设计。不可能从单个示例中猜测是否可以有超过1个二级节点。请注意,每个第三级节点都有一个子节点“StatusCode”。下面是一些粗略的代码,向您展示了(1)为什么需要STW_前缀caper(2)可用信息的摘录
import xml.etree.cElementTree as et
def showtag(elem):
return repr(elem.tag.rsplit("}")[1])
def showtext(elem):
return None if elem.text is None else repr(elem.text.strip())
root = et.fromstring(xml_response) # xml_response is your input string
print repr(root.tag) # see exactly what tag is in the element
for child in root[0]:
print showtag(child), showtext(child)
for gc in child:
print "...", showtag(gc), showtext(gc), gc.attrib
结果:
'{http://www.shrinktheweb.com/doc/stwresponse.xsd}ThumbnailResponse'
'ThumbnailResult' ''
... 'Thumbnail' None {'Exists': 'false'}
... 'Thumbnail' 'fix_and_retry' {'Verified': 'false'}
'ResponseStatus' ''
... 'StatusCode' 'Blank Detected' {}
'ResponseTimestamp' ''
... 'StatusCode' None {}
'ResponseCode' ''
... 'StatusCode' None {}
'CategoryCode' ''
... 'StatusCode' 'none' {}
'Quota_Remaining' ''
... 'StatusCode' '1' {}
如果您要显示正在使用的代码,可能会有所帮助……在Python 2.7+中,您可以使用register_namespace()来简化调用名称空间前缀的语法。@Liza Daly:文档中提到了序列化。它如何帮助解析现有的XML文档?