2015-12-12 106 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'。 謝謝! –