Searching Amazon for books through product search API

If you like to search for products on Amazon and include some of them in your website or application, this recipe can help you to do that. We can see how to search Amazon for books.

Getting ready

This recipe depends on the third-party Python library, bottlenose. You can install this library using pip, as shown in the following command:

$ pip install  bottlenose

First, you need to place your Amazon account's access key, secret key, and affiliate ID into local_settings.py. A sample settings file is provided with the book code. You can also edit this script and place it here as well.

How to do it...

We can use the bottlenose library that implements the Amazon's product search APIs.

Listing 8.7 gives the code for searching Amazon for books through product search APIs, as shown:

#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 8
# This program is optimized for Python 2.7.
# It may run on any other version with/without modifications.

import argparse
import bottlenose
from xml.dom import minidom as xml

try:
  from local_settings import amazon_account
except ImportError:
  pass 

ACCESS_KEY = amazon_account['access_key'] 
SECRET_KEY = amazon_account['secret_key'] 
AFFILIATE_ID = amazon_account['affiliate_id'] 


def search_for_books(tag, index):
  """Search Amazon for Books """
  amazon = bottlenose.Amazon(ACCESS_KEY, SECRET_KEY, AFFILIATE_ID)
  results = amazon.ItemSearch(
    SearchIndex = index,
    Sort = "relevancerank",
    Keywords = tag
  )
  parsed_result = xml.parseString(results)

  all_items = []
  attrs = ['Title','Author', 'URL']

  for item in parsed_result.getElementsByTagName('Item'):
    parse_item = {}

  for attr in attrs:
    parse_item[attr] = ""
    try:
      parse_item[attr] = 
item.getElementsByTagName(attr)[0].childNodes[0].data
    except:
      pass
    all_items.append(parse_item)
  return all_items

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Search info from 
Amazon')
  parser.add_argument('--tag', action="store", dest="tag", 
default='Python')
  parser.add_argument('--index', action="store", dest="index", 
default='Books')
  # parse arguments
  given_args = parser.parse_args()
  books = search_for_books(given_args.tag, given_args.index)    
  
  for book in books:
    for k,v in book.iteritems():
      print "%s: %s" %(k,v)
      print "-" * 80

If you run this recipe with a search tag and index, you can see some results similar to the following output:

$ python 8_7_search_amazon_for_books.py --tag=Python --index=Books
URL: http://www.amazon.com/Python-In-Day-Basics-Coding/dp/tech-data/1490475575%3FSubscriptionId%3DAKIAIPPW3IK76PBRLWBA%26tag%3D7052-6929-7878%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D1490475575
Author: Richard Wagstaff
Title: Python In A Day: Learn The Basics, Learn It Quick, Start Coding Fast (In A Day Books) (Volume 1)
--------------------------------------------------------------------------------
URL: http://www.amazon.com/Learning-Python-Mark-Lutz/dp/tech-data/1449355730%3FSubscriptionId%3DAKIAIPPW3IK76PBRLWBA%26tag%3D7052-6929-7878%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D1449355730
Author: Mark Lutz
Title: Learning Python
--------------------------------------------------------------------------------
URL: http://www.amazon.com/Python-Programming-Introduction-Computer-Science/dp/tech-data/1590282418%3FSubscriptionId%3DAKIAIPPW3IK76PBRLWBA%26tag%3D7052-6929-7878%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D1590282418
Author: John Zelle
Title: Python Programming: An Introduction to Computer Science 2nd Edition
---------------------------------------------------------------------
-----------

How it works...

This recipe uses the third-party bottlenose library's Amazon() class to create an object for searching Amazon through the product search API. This is done by the top-level search_for_books() function. The ItemSearch() method of this object is invoked with passing values to the SearchIndex and Keywords keys. It uses the relevancerank method to sort the search results.

The search results are processed using the xml module's minidom interface, which has a useful parseString() method. It returns the parsed XML tree-like data structure. The getElementsByTagName() method on this data structure helps to find the item's information. The item attributes are then looked up and placed in a dictionary of parsed items. Finally, all the parsed items are appended in a all_items()list and returned to the user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.151.45