本文整理汇总了Python中amazonproduct.API类的典型用法代码示例。如果您正苦于以下问题:Python API类的具体用法?Python API怎么用?Python API使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了API类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_similar_books
def get_similar_books(ASIN):
api = API(AWS_KEY, SECRET_KEY, 'us', ASSOCIATE_TAG)
for root in api.similarity_lookup(str(ASIN)):
try:
current_page = root.Items.Request.ItemSearchRequest.ItemPage.pyval
except AttributeError:
current_page = 1
#print 'page %d of %d' % (current_page, total_pages)
nspace = root.nsmap.get(None, '')
books = root.xpath('//aws:Items/aws:Item', namespaces={'aws' : nspace})
similar_items = []
i = 0
for book in books:
if (i==3):
return similar_items
similar_items.append(book)
i = i + 1
示例2: search_on_amazon
def search_on_amazon(asin, album, artist):
'''
Tries to locate the url of album by artis on amazon
Returns '' if it can't be found
'''
from amazonproduct import API
if not AMAZON_KEY or not AMAZON_SECRET or not AMAZON_ASSOCIATE_TAG:
return ''
api = API(AMAZON_KEY, AMAZON_SECRET, 'us')
try:
if asin:
node = api.item_lookup(asin, AssociateTag=AMAZON_ASSOCIATE_TAG)
for item in node.Items:
attributes = item.Item.ItemAttributes
if attributes.ProductGroup == 'Music':
url = item.Item.DetailPageURL
if url:
return url.text
node = api.item_search('MP3Downloads', Keywords=album + ' ' + artist, AssociateTag=AMAZON_ASSOCIATE_TAG)
for item in node.Items:
attributes = item.Item.ItemAttributes
if matching.match(artist, str(attributes.Creator)) \
and matching.match(album, str(attributes.Title)) \
and attributes.ProductGroup == 'Digital Music Album':
url = item.Item.DetailPageURL
if url:
return url.text
except :
pass
return ''
示例3: lookup_price
def lookup_price(searchTerm):
AWS_KEY = 'AKIAIILUNE5IYH7BDF2A'
SECRET_KEY = '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'
ASSOC_TAG = 'camerarecomm-20'
api = API(AWS_KEY, SECRET_KEY, 'us', ASSOC_TAG)
price = -1
title = ''
try:
results = api.item_search('Electronics', Keywords=searchTerm,
BrowseNode='281052', ResponseGroup='Large', ItemPage=1)
if results is not None:
for cam in results:
try:
#asin = cam.Items.Item.ASIN
title = cam.Items.Item.ItemAttributes.Title.text
price = cam.Items.Item.ItemAttributes.ListPrice.FormattedPrice.text
# print title, price
break
except:
price = -1
title = ''
except:
print 'Item not found'
return price, title
示例4: pullItemInfoFromAmazon
def pullItemInfoFromAmazon(job_id):
logger = logging.getLogger('tst')
asin_obj_list = Asin.objects.filter(job_id = job_id)
asin_list = [x.asin for x in asin_obj_list]
pull_fail_list = []
insert_fail_list = []
image_fail_list = []
api = API(access_key_id = ACCESS_KEY_ID, secret_access_key = SECRET_ACCESS_KEY, associate_tag = ASSOCIATE_TAG, locale='us')
for asin in asin_list[:10]:
asin = asin.strip()
result = ''
for i in range(0,2):
try:
result = api.item_lookup(asin,ResponseGroup='Images,ItemAttributes,Offers,BrowseNodes',MerchantId = 'Amazon',Condition='New')
logger.info('ASIN: %s -- %d time -- Success'%(asin,i+1))
break
except Exception,e:
logger.info('ASIN: %s -- %d time -- Fail'%(asin,i+1))
continue
if result == '':
logger.info('ASIN: %s Fail after 3 times'%asin)
pull_fail_list.append(asin)
continue
if not insert_item_info(result,asin):
logger.error('Insert item info for %s fail'%asin)
insert_fail_list.append(asin)
continue
if not process_image(asin):
logger.error('Processing Image for %s fail'%asin)
image_fail_list.append(asin)
continue
示例5: show_product
def show_product(locale, asin):
api = API(locale=locale)
result = api.item_lookup(asin, ResponseGroup="ItemIds, ItemAttributes, Images, OfferSummary, Offers")
niceProduct = Product()
for product in result.Items.Item:
niceProduct.title = product.ItemAttributes.Title
niceProduct.ASIN = product.ASIN.text
niceProduct.imageUrl = product.MediumImage.URL
try:
niceProduct.newPrice = float(product.OfferSummary.LowestNewPrice.Amount)/100
niceProduct.newFormattedPrice = product.OfferSummary.LowestNewPrice.FormattedPrice
niceProduct.newPriceCurrency = product.OfferSummary.LowestNewPrice.CurrencyCode
except:
pass
try:
niceProduct.usedPrice = float(product.OfferSummary.LowestUsedPrice.Amount)/100
niceProduct.usedFormattedPrice = product.OfferSummary.LowestUsedPrice.FormattedPrice
niceProduct.usedPriceCurrency = product.OfferSummary.LowestUsedPrice.CurrencyCode
except:
pass
niceProduct.type = product.ItemAttributes.ProductGroup
niceProduct.region = getRegionFromUrl(product.DetailPageURL.text).upper() #product.ItemAttributes.RegionCode
niceProduct.model = product.ItemAttributes.Model
return render_template('product.html', product = niceProduct)
示例6: test_associate_tag_is_written_to_url
def test_associate_tag_is_written_to_url(self):
tag = 'ABC12345'
api = API(self.ACCESS_KEY, self.SECRET_KEY, 'de', associate_tag=tag)
url = api._build_url(Operation='ItemSearch', SearchIndex='Books')
qs = parse_qs(urlparse(url)[4])
assert qs['AssociateTag'][0] == tag
示例7: services_incoming
def services_incoming(request):
"""We have an incoming item (probably from the bookmarklet)"""
#TODO: this is nothing more than a test now. cleanup.
url = request.GET.get('loc', None)
matches = re.search(r'\/([A-Z0-9]{10})($|\/)', url)
asin = matches.group(1)
aws_key = AMZ.KEY
aws_secret_key = AMZ.SECRET_KEY
api = API(aws_key, aws_secret_key, 'us')
for root in api.item_lookup(asin, IdType='ASIN', AssociateTag= AMZ.ASSOCIATE_TAG):
nspace = root.nsmap.get(None, '')
amazon_items = root.xpath('//aws:Items/aws:Item', namespaces={'aws' : nspace})
author = u'Unknown'
title = u'Unknown'
isbn = u'Unknown'
for amazon_item in amazon_items:
if hasattr(amazon_item.ItemAttributes, 'Author'):
author = unicode(amazon_item.ItemAttributes.Author)
if hasattr(amazon_item.ItemAttributes, 'Title'):
title = unicode(amazon_item.ItemAttributes.Title)
return render_to_response('add-item.html', {'user': request.user, 'creator': author, 'title': title, 'isbn': isbn})
示例8: search
def search(title=''):
"""Amazon quick search function."""
api = API(LOG['AWS_KEY'], LOG['SECRET_KEY'], LOG['LOCAL'], LOG['ASSOC_TAG'])
node = api.item_search('Books', Title=title, Publisher=publisher)
for page in node:
for book in page.Items.Item:
print '%s' % (book.ASIN)
示例9: lookup
def lookup(asin):
api = API(locale="jp")
# item = api.item_lookup(asin, ResponseGroup='OfferFull', Condition='All')
# item = api.item_lookup(asin)
item = api.item_lookup(asin, ResponseGroup="Large")
# logging.debug(etree.tostring(item, pretty_print=True))
## title
logging.debug(item.Items.Item.ItemAttributes.Title)
示例10: search
def search():
api = API(locale="jp")
# total_results = node.Items.TotalResults.pyval
# total_pages = node.Items.TotalPages.pyval
for book in api.item_search("Books", Publisher=u"村上"):
try:
print "%s" % (book.ItemAttributes.Title)
# print '%s: "%s"' % (book.ItemAttributes.Author,
# book.ItemAttributes.Title)
except:
logging.debug("no author or title")
示例11: search
def search(self, q, country):
titles = []
prices = []
urls= []
items = []
api = API(AWS_KEY, SECRET_KEY, country)
try:
for root in api.item_search('Books', Title=q, AssociateTag='...', ResponseGroup='Large'):
# extract paging information
total_results = root.Items.TotalResults.pyval
total_pages = root.Items.TotalPages.pyval
try:
current_page = root.Items.Request.ItemSearchRequest.ItemPage.pyval
except AttributeError:
current_page = 1
#print 'page %d of %d' % (current_page, total_pages)
#~ from lxml import etree
#~ print etree.tostring(root, pretty_print=True)
nspace = root.nsmap.get(None, '')
books = root.xpath('//aws:Items/aws:Item',
namespaces={'aws' : nspace})
#return unicode(books[0].ItemAttributes.Title)
for book in books:
items.append(unicode(book.ItemAttributes.Title))
#print book.ASIN,
#if hasattr(book.ItemAttributes, 'Author'):
#print unicode(book.ItemAttributes.Author), ':',
#print unicode(book.ItemAttributes.Title),
#price_offers(book.ASIN)
try:
if hasattr(book.ItemAttributes, 'ListPrice'):
#print unicode(book.ItemAttributes.ListPrice.FormattedPrice)
items.append(unicode(book.ItemAttributes.ListPrice.FormattedPrice))
elif hasattr(book.OfferSummary, 'LowestUsedPrice'):
#print u'(used from %s)' % book.OfferSummary.LowestUsedPrice.FormattedPrice
items.append(unicode(book.OfferSummary.LowestUsedPrice.FormattedPrice))
except:
items.append("No price info.")
items.append(unicode(book.DetailPageURL))
#print '\n'
#print len(items)
return items
except:
return items
示例12: pytest_generate_tests
def pytest_generate_tests(metafunc):
# called once per each test function
if 'api' in metafunc.funcargnames and 'operation' in metafunc.funcargnames:
for version in TESTABLE_API_VERSIONS:
wsdl = os.path.join(XML_TEST_DIR, version,
'AWSECommerceService.wsdl')
if not os.path.exists(wsdl):
continue
api = API('', '', 'de')
api.VERSION = version
for operation in extract_operations_from_wsdl(wsdl):
metafunc.addcall(
id='%s/%s' % (version, operation),
funcargs={'api' : api, 'operation' : operation})
示例13: __init__
class AmazonUtil:
def __init__(self):
#self.associate_tag = settings.ASSOCIATE_TAG
#self.access_key_id = settings.ACCESS_KEY_ID
#self.secret_access_key = settings.SECRET_ACCESS_KEY
self.api = None
def item_lookup(self,asin,locale,retry=3,time_interval=10,ResponseGroup='Images,ItemAttributes,Offers,BrowseNodes',MerchantId=None,Condition=None):
self.api = API(access_key_id = settings.ACCESS_KEY_ID, secret_access_key = settings.SECRET_ACCESS_KEY, associate_tag = settings.ASSOCIATE_TAG, locale=locale)
result = ''
#status
#0 -- Success
#1 -- Socket Timeout
#2 -- Invalid ASIN
#-1 -- Fail
status = -1
for i in range(0,retry):
try:
#result = self.api.item_lookup(asin,ResponseGroup=ResponseGroup,MerchantId = MerchantId,Condition=Condition)
result = self.api.item_lookup(asin,ResponseGroup=ResponseGroup)
status = 0
break
except urllib2.URLError,e:
status = 1
continue
except socket.timeout,e:
status = 1
continue
except InvalidParameterValue,e:
status = 2
break
示例14: AmazonMovies
class AmazonMovies(object):
def __init__(self, titles):
self._pattern1 = re.compile(r"(\[.*\]|\(.*\)|【.*】|<.*>|(.*)|〔.*〕)")
self._pattern2 = re.compile(r"(DVD|Blu-ray|ブルーレイ|枚組).*")
self._pattern3 = re.compile(r"\s.*(MovieNEX|2D|3D|エディション|ディスク|特別(編|版)).*")
self._pattern4 = re.compile(r"\s$")
self._api = API(cfg=amazon_keys.config)
self._input_movies = self.get_movie_dict(titles)
self.movies_dict = self.get_similarproducts(self._input_movies)
self.movies = self.get_titles(self.movies_dict)
def get_movie_dict(self, titles):
tmp_list = []
for title in titles:
tmp_list.append({'title': title, 'asin': self.get_asin(title)})
return tmp_list
def get_asin(self, title):
time.sleep(2) # 1.8sのインターバルあれば制限に引っかからない?
asin = u""
try:
for items in self._api.item_search('DVD', Keywords=title, limit=1):
for item in items:
asin = unicode(item.ASIN)
break
break
except AWSError, e:
print("code:%s message:%s" % (e.code, e.message))
return asin
示例15: main
def main(self):
# Amazon consists of multiple webshops from different countries.
for locale in self.locales:
productDataList = []
self.api = API(locale=locale)
products = self.loadProducts(locale)
for product in products:
if product != '' and product is not None and product[0] != '#': # Comment or blank line.
# Product contains two elements: The ASIN and the shipping cost, divided by `:`.
product = product.split(':')
ASIN = product[0]
productData = self.gatherData(ASIN, locale)
if productData is not None: # Something went wrong retrieving data.
productData["shipping_cost"] = product[1]
# Add the product data to a list so we can convert the list to xml once all products are parsed.
productDataList.append(productData)
time.sleep(2)
self.writeXML(productDataList, locale)