2015-12-12 35 views
0

我试图通过它们的API搜索Pastebin上的内容。我正在使用python的pastebin库进行搜索。在Python中解析XML 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_title == goodPaste返回paste_key,但ATTRIB总是空

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_keypaste_title == goodPaste

EDIT 2 中奖元素:

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

那是因为你没有显示什么属性,只有标签数据。你访问它的方式是说'.text'不是'.attrib' –

+0

@JavierBuzzi你是一个天才!谢谢!我错过了ElementTree文档。再次感谢你! –

+0

Np。如果你迷路了,这里是文档。 https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.text –

回答

1

您可以使用XPath为:

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

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

+0

它工作,但为了清楚起见,'result'是一个列表,所以我打印'result [0] .text'。 谢谢! –