如何使用Python xml.etree.ElementTree解析eBay API响应?
我正在尝试使用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')
,但都没有成功。
有没有人能教我怎么用一些Python的库来处理这个API?我看到过easyBay、ebay-sdk-python和pyeBay,但是我没能让它们实现我想要的功能。有没有值得使用的eBay Python API呢?
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 支持的解释 来了解更多。