get xml's elements with namespace from Amazon Product API with lxml and Python3

You have to add namespace before every prefix like below.

import xml.etree.ElementTree as ET
root = ET.fromstring(xml) # prepare xml
nspace = '{http://webservices.amazon.com/AWSECommerceService/2013-08-01}'
for item in root.findall('.//'+nspace+'Items/'+nspace+'Item/'+nspace+'ItemAttributes/'+nspace+'Title'):
    print(item.text, item.attrib)

# or simpler way
for item in root.findall('.//ns:Items/ns:Item/ns:ItemAttributes/ns:Title', namespaces={'ns':'http://webservices.amazon.com/AWSECommerceService/2013-08-01'}):
    print(item.text, item.attrib)


Also, beware that findall() only finds direct children like parent.findall(children).
findall() returns a list, find() not.

cf)
XPath and XSLT with lxml

コメント

人気の投稿