如何使用ElementTree解析web xml

时间:2011-03-30 01:20:57

标签: python elementtree

我正在尝试使用缩小网站服务的网站缩略图。他们有一个返回XML的API,告诉您是否可以创建站点缩略图。我正在尝试使用ElementTree来解析xml,但不知道如何获取我需要的信息。以下是XML响应的示例:

<?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>

我需要获取“stw:StatusCode”。如果我尝试在“stw:StatusCode”上进行查找,则会出现“预期路径分隔符”语法错误。有没有办法获得状态代码?

1 个答案:

答案 0 :(得分:1)

Grrr名称空间....试试这个:

STW_PREFIX = "{http://www.shrinktheweb.com/doc/stwresponse.xsd}"

(参见示例XML的第2行)

然后,当您需要stw:StatusCode这样的标记时,请使用STW_PREFIX + "StatusCode"

更新:XML响应不是最精彩的设计。从单个示例中猜测是否可以存在多于1个第二级节点是不可能的。请注意,每个第3级节点都有一个“StatusCode”子节点。下面是一些粗略的代码,向您展示(1)为什么需要STW_PREFIX 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' {}