how to use python xml.etree.ElementTree to parse eBay API response?
I am trying to use xml.etree.ElementTree to parse responses from eBay finding API, findItemsByProduct. After lengthy trial and error, I came up with this code开发者_StackOverflow中文版 which prints some data:
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
But that seems not very elegant, how can I get the 'itemId' and 'title' without looping over all attributes and checking if it is the one I want? I tried using things like .get(namespace + 'itemId')
and .find(namespace + 'itemId')
and .attrib.get(namespace + 'itemId')
but nothing really worked.
Can someone maybe show me how to do this using some python wrapper for this API? I saw easyBay, ebay-sdk-python and pyeBay but I didn't manage to get any of them to do what I want. Is there any eBay python API which is worthwhile to use for this?
You can use ElementTree
. If you want to get the items you can use findall and the path to the items, then iterate over the list of items:
items = root.findall(namespace+'searchResult/'+namespace+'item')
for item in items:
item.find(namespace+'itemId').text
item.find(namespace+'title').text
To get directly to the first itemId from the root:
root.find(namespace+'searchResult/'+namespace+'item/'+namespace+'itemId')
Basically, the find method uses XPath to retrieve elements more than one level below the subelements. See also Effbot's explanation of XPath support in ElementTree
精彩评论