【问题标题】:how to use python xml.etree.ElementTree to parse eBay API response?如何使用 python xml.etree.ElementTree 解析 eBay API 响应?
【发布时间】:2011-05-05 20:34:12
【问题描述】:

我正在尝试使用 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').find(namespace + 'itemId').attrib.get(namespace + 'itemId') 之类的东西,但没有任何效果。

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

【问题讨论】:

    标签: python xml xmlhttprequest ebay-api


    【解决方案1】:

    您可以使用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's explanation of XPath support in ElementTree

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多