簡體   English   中英

在Python中解析XML Pastebin響應

[英]Parsing XML Pastebin response, in Python

我正在嘗試通過他們的API在Pastebin上進行搜索。 我正在使用pastebin庫搜索python。

問題是我收到一個具有重復鍵的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_keypaste_title == goodPaste ,但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

編輯2中獎彩票:

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

您可以為此使用XPath:

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

這應該在您的情況下打印fsfgdsgg

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM