0

我正在尝试通过他们的 API 在 Pastebin 上搜索一些东西。我正在使用 python 的 pastebin 库进行搜索。

问题是我收到了一个包含重复键的 XML 响应。

这是回应

<paste>
<paste_key>fadsda</paste_key>
<paste_date>1409074286</paste_date>
<paste_title>badPaste</paste_title>
<paste_size>2040</paste_size>
<paste_expire_date>0</paste_expire_date>
<paste_private>0</paste_private>
<paste_format_long>Bash</paste_format_long>
<paste_format_short>bash</paste_format_short>
<paste_url>http://pastebin.com/url2</paste_url>
<paste_hits>211</paste_hits>
</paste>
<paste>
<paste_key>fsfgdsgg</paste_key>
<paste_date>1398409838</paste_date>
<paste_title>goodPaste</paste_title>
<paste_size>2407</paste_size>
<paste_expire_date>0</paste_expire_date>
<paste_private>2</paste_private>
<paste_format_long>Bash</paste_format_long>
<paste_format_short>bash</paste_format_short>
<paste_url>http://pastebin.com/otherURL</paste_url>
<paste_hits>54</paste_hits>
</paste>

所以我试图解析它以返回paste_keywhen paste_title == goodPaste,但属性始终为空

def parseXML(response):
    #I'm adding a root tag
    xml = ElementTree.fromstring('<list>' + response + '</list>')
    for child in root:
            for elem in child:
                print elem.tag, elem.attrib

返回

    paste_key {}
    paste_date {}
    paste_title {}
    paste_size {}
    paste_expire_date {}
    paste_private {}
    paste_format_long {}
    paste_format_short {}
    paste_url {}
    paste_hits {}
    paste_key {}
    paste_date {}
    paste_title {}
    paste_size {}
    paste_expire_date {}
    paste_private {}
    paste_format_long {}
    paste_format_short {}
    paste_url {}
    paste_hits {}

编辑:所以我应该使用 elem.text,所以现在可以使用,但主要问题仍然存在:我如何才能在paste_key何时返回元素paste_title == goodPaste

编辑 2 中奖彩票:

result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result[0].text
4

1 回答 1

1

您可以为此使用 XPath:

result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result.text

fsfgdsgg这应该在您的情况下打印

于 2015-12-12T17:02:44.200 回答