我試圖通過它們的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_key
時paste_title == goodPaste
EDIT 2 中獎元素:
result = xml.findall(".//paste[paste_title='goodPaste']/paste_key")
print result[0].text
那是因爲你沒有顯示什麼屬性,只有標籤數據。你訪問它的方式是說'.text'不是'.attrib' –
@JavierBuzzi你是一個天才!謝謝!我錯過了ElementTree文檔。再次感謝你! –
Np。如果你迷路了,這裏是文檔。 https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.text –