Python ElementTree でAmazon APIを利用する

この間、SAXパーサーでAmazon Product(以下略)を解析したので、更なるXML柔軟利用を目指してXPathを使ってみる。

Amazon APIへのRESTリクエスト作成はこちら。また、最新のソースはこのあたり

ElementTree 参考URL

XPath の構文

注意点

  • xmlns属性があると、タグを指定するときに、’//tag_name’ などと書くことができずに、’//{http://xmlns_attribute_value}tag_name’のようにいちいち記述する必要がある。
  • 要するに、elm.find(‘./ItemAttributes/Title’) と書くことはできず、elm.find(‘./{http://webservices.amazon.com/AWSECommerceService/2005-10-05}ItemAttributes/{http://webservices.amazon.com/AWSECommerceService/2005-10-05}Title のようにする必要がある’)
  1. #!Python2.6
  2. # -*- coding: utf-8 -*-
  3.  
  4. import amazon_ecs # 自作モジュールをインポート
  5. import urllib2
  6. from xml.etree import ElementTree
  7.  
  8. # xmlns を付加したタグ名を返す
  9. def qn(tag):
  10. return ElementTree.QName(ns, tag).text
  11.  
  12. ns = r'http://webservices.amazon.com/AWSECommerceService/2005-10-05'
  13.  
  14. # xmlnsが指定されている場合、タグを{xmlnsの値}タグ名 といちいち書く必要があるため、そのように展開したものを保持しておく
  15. # ./{http://webservices.amazon.com/AWSECommerceService/2005-10-05}ItemAttributes/{http://webservices.amazon.com/AWSECommerceService/2005-10-05}Title
  16. q_items = './/{0}'.format(qn('Item'))
  17. q_title = './{0}/{1}'.format(qn('ItemAttributes'), qn('Title'))
  18. q_author = './{0}/{1}'.format(qn('ItemAttributes'), qn('Author'))
  19. q_asin = './{0}'.format(qn('ASIN'))
  20. q_url = './{0}'.format(qn('DetailPageURL'))
  21. q_img = './{0}/{1}'.format(qn('SmallImage'), qn('URL'))
  22.  
  23. # Amazon Product Advertise API リクエスト URLを生成
  24. operation = amazon_ecs.ItemSearch()
  25. operation.keywords('手塚 治虫')
  26. operation.search_index('Books')
  27. operation.response_group('Large')
  28. request = operation.request()
  29. print 'REQUEST : {0}'.format(request)
  30.  
  31. # ElementTreeを生成
  32. root = ElementTree.parse(urllib2.urlopen(request)).getroot()
  33. # XPathを使用してElementTreeを解析
  34. items = root.findall(q_items)
  35. for item in items:
  36. print '-' * 100
  37. print 'TITLE : {0}'.format(item.find(q_title).text)
  38. print 'AUTHOR : {0}'.format(item.find(q_author).text)
  39. print 'ASIN : {0}'.format(item.find(q_asin).text)
  40. print 'URL : {0}'.format(item.find(q_url).text)
  41. print 'IMG : {0}'.format(item.find(q_img).text)

PyDevで走らせた結果

py_xpath01

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

前の記事

初めてのPython