4

我正在尝试使用 xml.etree.ElementTree 来解析来自 eBay 查找 API、findItemsByProduct 的响应。经过长时间的试验和错误,我想出了这个打印一些数据的代码:

import urllib
from xml.etree import ElementTree as ET

appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
isbn = '3868731342'

namespace = '{http://www.ebay.com/marketplace/search/v1/services}'

url = 'http://svcs.ebay.com/services/search/FindingService/v1?' \
    + 'OPERATION-NAME=findItemsByProduct' \
    + '&SERVICE-VERSION=1.0.0' \
    + '&GLOBAL-ID=EBAY-DE' \
    + '&SECURITY-APPNAME=' + appID \
    + '&RESPONSE-DATA-FORMAT=XML' \
    + '&REST-PAYLOAD' \
    + '&productId.@type=ISBN&productId=' + isbn

root = ET.parse(urllib.urlopen(url)).getroot()

for parts in root:
    if parts.tag == (namespace + 'searchResult'):
        for item in list(parts):
            for a in list(item):
                if a.tag == (namespace + 'itemId'):
                    print 'itemId: ' + a.text
                if a.tag == (namespace + 'title'):
                    print 'title: ' + a.text

但这似乎不是很优雅,我怎样才能得到'itemId'和'title'而不循环所有属性并检查它是否是我想要的?我尝试使用诸如.get(namespace + 'itemId')and之类的东西.find(namespace + 'itemId').attrib.get(namespace + 'itemId')但没有任何效果。

有人可以告诉我如何使用这个 API 的一些 python 包装器来做到这一点吗?我看到了easyBayebay-sdk-pythonpyeBay,但我没有设法让他们中的任何一个做我想做的事。是否有任何值得为此使用的 eBay python API?

4

1 回答 1

4

您可以使用ElementTree. 如果要获取可以使用 findall 的项目和项目的路径,然后遍历项目列表:

items = root.findall(namespace+'searchResult/'+namespace+'item')
for item in items: 
     item.find(namespace+'itemId').text
     item.find(namespace+'title').text

要从根目录直接获取第一个 itemId:

root.find(namespace+'searchResult/'+namespace+'item/'+namespace+'itemId')

基本上,find 方法使用 XPath 来检索子元素下一层以上的元素。另请参阅Effbot 在 ElementTree 中对 XPath 支持的解释

于 2010-11-05T22:49:25.160 回答