This is a script which takes an Amazon URL as input, takes out ASIN/ISBN from the URL, and uses Amazon Python API to fetch details.
For this task, I looked at many Amazon URLs and observed the following things:
- ASIN/ISBN is always present in an Amazon URL
- ASIN/ISBN can be present anywhere in the URL
- ASIN is always in capital letters, consists of alphabets and numbers only and length is always 10
- If ASIN is not present then it's a link to a book on Amazon and ISBN will be present
- ISBN consists only of numbers
- Amazon uses ISBN-10 format i.e. length of ISBN is 10
- Haven't come across ASIN which is purely numbers and without any alphabets
- ASIN or ISBN, always followed by '/'
I hope I covered everything, but if I missed some case, please let me know.
Secondly, I care about only Amazon India. So it throws that ASIN is invalid if I give an ASIN of Amazon US or any other country, or gives pricing info zero. I don't know why it is causing such behaviour (example).
Flow: Get the URL, check for either ASIN or ISBN, if none are present return false else use API to fetch name, price, URL and product image.
import re
from amazon.api import AmazonAPI
AMAZON_ACCESS_KEY = 'AKI...JP2'
AMAZON_SECRET_KEY = 'Eto...uxV'
AMAZON_ASSOC_TAG = 'p...1'
asin_regex = r'/([A-Z0-9]{10})'
isbn_regex = r'/([0-9]{10})'
def get_amazon_item_id(url):
# return either ASIN or ISBN
asin_search = re.search(asin_regex, url)
isbn_search = re.search(isbn_regex, url)
if asin_search:
return asin_search.group(1)
elif isbn_search:
return isbn_search.group(1)
else:
# log this URL
return None
def get_amazon_product_meta(url):
# the input URL is always of amazon
amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG, region="IN")
item_id = get_amazon_item_id(url)
if not item_id:
return None
try:
product = amazon.lookup(ItemId=item_id)
except amazon.api.AsinNotFound:
# log this ASIN
return None
# product.price_and_currency returns in the form (price, currency)
product_price = product.price_and_currency[0]
if product_price:
return product.offer_url, product.title, product.large_image_url, product_price
return None