2016-09-06 61 views
0

API請求:http://iss.ndl.go.jp/api/opensearch?isbn=9784334770051如何使用Python解析XML值2.7

我需要從上面通過API提供的XML中獲取一個特定值。 我嘗試從<item>以及<dc:title>的值中獲取所有值,具體爲 以下是我當前的代碼,嘗試從項目中獲取所有值但未起作用。

import codecs 
import sys 
import urllib 
import urllib2 
import re, pprint 
from xml.etree.ElementTree import * 
import csv 
from xml.dom import minidom 
import xml.etree.ElementTree as ET 

errorCheck = "0" 
isbn = raw_input("Enter IBSN Number Please ") 
isIsbn = len(isbn) 


if isIsbn == 10 or isIsbn == 13: 
    errorCheck = 1; 

    url = "http://iss.ndl.go.jp/api/opensearch?isbn=%s" % isbn 
    req = urllib2.Request(url) 

    response = urllib2.urlopen(req) 
    XmlData = response.read() 
    root = ET.fromstring(XmlData) 

    print(root.tag,root.attrib) 

    for child in root.find('item'): 
     print child.tag 
     print child.attrib 
     print child.text 

if errorCheck == "0": 
    print "It is not ISBN" 
+0

元樹,但要求所有密鑰都是唯一的!作爲字符串解析,更多的XML文件沒有完整的質量數據模式。 – dsgdfg

回答

1

<item>不是根元素的直接子,所以你不能直接提到元素(root.find('item'))找到它。您可以在根中使用.//item找到item元素的任何地方:

for child in root.find('.//item'): 

或指定從根到<item>的準確路徑:

for child in root.find('channel/item'): 

至於尋找<dc:title>元素,請參閱:Parsing XML with namespace in Python via 'ElementTree'

+0

謝謝!我會試試! –

+0

命名空間= {「DC」:根}#添加更多需要 \t打印root.findall(「DC:標題」,命名空間) 我目前正在嘗試,但我認爲我不理解你所提供的鏈接。 你給我的代碼工作正常。 解析ElementTree需要什麼? –

+0

@KeiroKamioka在開頭加上'.//',因爲我在這個回答中提到過:'root.findall('.// dc:title',namespaces)' – har07