当前位置: 首页>>代码示例>>Python>>正文


Python API.item_lookup方法代码示例

本文整理汇总了Python中amazonproduct.API.item_lookup方法的典型用法代码示例。如果您正苦于以下问题:Python API.item_lookup方法的具体用法?Python API.item_lookup怎么用?Python API.item_lookup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在amazonproduct.API的用法示例。


在下文中一共展示了API.item_lookup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: services_incoming

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
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})
开发者ID:imakewebthings,项目名称:shlvme,代码行数:29,代码来源:views.py

示例2: show_product

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
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)
开发者ID:ronangaillard,项目名称:amazon-price-tracker,代码行数:31,代码来源:main.py

示例3: __init__

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
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
开发者ID:kuang1987,项目名称:amazon-item-poll-job,代码行数:34,代码来源:amazon_util.py

示例4: pullItemInfoFromAmazon

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
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
开发者ID:kuang1987,项目名称:amazon-item-poll-job,代码行数:35,代码来源:tasks_bak.py

示例5: search_on_amazon

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
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 ''
开发者ID:GunioRobot,项目名称:music-inbox,代码行数:35,代码来源:models.py

示例6: lookup

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
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)
开发者ID:tanarky,项目名称:sample-codes,代码行数:11,代码来源:search.py

示例7: get_product_details

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
 def get_product_details(cls,asin,product_renderer,locale = 'us'):
   
   logging.info('AmazonProductFetcher.get_product_details called, asin: %s, locale: %s' %(asin,locale))
   api = API(AWS_KEY, SECRET_KEY, locale)
   timeout_ms = 100
   while True:
     try:
       product_node = api.item_lookup(id=asin)  #title,product group
       image_node = api.item_lookup(id=asin, ResponseGroup='Images') #Images
       break
     except amazonproduct.TooManyRequests:
       time.sleep(timeout_ms)
       timeout_ms *= 2                            
     except AWSError:
       logging.error('Could not retrieve info for product %s' % asin)
       return
     except DownloadError,e:
       logging.error('%s retrieving URLfor product: %s in RPC'   %(e,asin))
       return #Early quit
开发者ID:frankk00,项目名称:TweetHit,代码行数:21,代码来源:rpc.py

示例8: request_amzn

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
def request_amzn (isbn):
	r"""
	Get The Book Title and asin code from Amazon.

	:param isbn: ISBN string
	:return: tuple (Book titile, Asin Code, XML RootNode)
	"""

	api = API(locale='jp')
	root = api.item_lookup(isbn,SearchIndex='Books', IdType='ISBN')

	root = api.item_lookup(isbn,SearchIndex='Books', IdType='ISBN')
	book = root.xpath(
		"//aws:Items/aws:Item/aws:ItemAttributes/aws:Title",
		namespaces={"aws": root.nsmap.get(None, '')}
	)
	asin = root.xpath(
		"//aws:Items/aws:Item/aws:ASIN",
		namespaces={"aws": root.nsmap.get(None, '')}
	)
	return (book, asin, root)
开发者ID:a-yasui,项目名称:amazon-isbn-get,代码行数:23,代码来源:csv_read_and_change.py

示例9: Amazon

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
class Amazon():

    def __init__(self, url, locale='us'):
        self.api = API(locale=locale)
        self.asin = self.__get_product_id(url)
        self.result = self.api.item_lookup(
            self.asin,
            ResponseGroup='ItemAttributes,Offers,Images'
        )
        try:
            self.item = self.result.Items.Item[0]
        except IndexError:
            self.item = None

    def __get_product_id(self, url):
        """ get a amazon asin number from url """
        compiled_pattern = re.compile("([A-Z0-9]{10})")
        search_result = compiled_pattern.search(url)
        try:
            return search_result.group(0)
        except IndexError:
            return None

    @property
    def title(self):
        """ return title of Item """
        return self.item.ItemAttributes.Title.text

    @property
    def price(self):
        """ return lowest price of Amazon Item """
        try:
            return self.item.OfferSummary.LowestNewPrice.FormattedPrice.text
        except AttributeError:
            return None

    @property
    def currency(self):
        """ return currency of Amazon Item """
        try:
            return self.item.OfferSummary.LowestNewPrice.CurrencyCode
        except AttributeError:
            return None

    @property
    def photo(self):
        """ return small Image of Amazon Item """
        try:
            return self.item.SmallImage.URL.text
        except AttributeError:
            return None
开发者ID:sandlbn,项目名称:drawn,代码行数:53,代码来源:amazon.py

示例10: __init__

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
class Amazon:
    def __init__(self):
        self.api             = API(locale='us'); 
        self.cart_exists     = False
        self.items = {}

    def get_asin_from_url(self, url):
        parts = urlparse(url)
        path_parts = parts.path.split("/")

        max = len(path_parts)-1
        reg = re.compile("^([A-Za-z0-9]{10})$")
        while max >= 0:
            result = reg.match(path_parts[max])
            if result:
                return path_parts[max]
            max = max-1
        return None

    def get_item_by_asin(self, asin):
        item = self.api.item_lookup(asin)
        return item

    def get_items(self, list):
        items = Item.objects.filter(active=True, list=list)

        for item in items:
            self.items["%s" % item.asin] = item.quantity

    def get_cart(self):
        cart = self.api.cart_create(self.items)

        print cart.Cart.PurchaseURL
        print cart.Cart.SubTotal.FormattedPrice

        # May need this at some point?
        """
        for item in cart.Cart.CartItems:
            print dir(item.CartItem)
        """
        return cart

    def main(self):
        self.get_items()
        self.get_cart()
开发者ID:bmelton,项目名称:SupportClassrooms,代码行数:47,代码来源:amazon.py

示例11: amazon_lookup

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
def amazon_lookup(asin):
	api = API(locale='us')

	
	result = api.item_lookup(asin, ResponseGroup="ItemAttributes, OfferSummary", paginate = False)


	it = result.Items.Item
	asin = it.ASIN
	title = it.ItemAttributes.Title
	link = it.DetailPageURL
	
	try:
		price = it.OfferSummary.LowestNewPrice.FormattedPrice
	except:
		price = "no price available"
				
	item = {'asin':asin, 'title':title, 'link':link, 'price':price}
		
	return item
开发者ID:sharangdhar,项目名称:Cookingtime,代码行数:22,代码来源:item_views.py

示例12: scrape_wish_list_items

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
def scrape_wish_list_items(list_id):
    """ Populate wish_list_items with data from wishlist """
    print "Scraping wishlist..."

    wish = Wishlist(list_id)
    item_ids = wish.get_list_items()

    wishlist_items = []

    api = API(locale='us')
    for item_id in item_ids:
        try:
            result = api.item_lookup(item_id, ResponseGroup="Large")
            for item in result.Items.Item:
                itm = { "title": item.ItemAttributes.Title, "price": item.Offers.Offer.OfferListing.Price.FormattedPrice, "amazonid": item.ASIN }
                wishlist_items.append(itm)
        except:
            print "!!! Failed getting " + item_id

    print "Completed scraping."
    return wishlist_items
开发者ID:kylefrost,项目名称:wishlist-price-checker,代码行数:23,代码来源:amazon.py

示例13: create_wish_from_url

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
def create_wish_from_url(user, url):
    AWS_KEY = os.environ['AWS_KEY']
    AWS_SECRET_KEY = os.environ['AWS_SECRET_KEY']
    ASSOCIATE_TAG = os.environ['ASSOCIATE_TAG']
    ASIN_MATCH = 'http://www.amazon.com/([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})'

    asin = list(re.match(ASIN_MATCH, url).groups())[-1]

    api = API(locale='us',
              associate_tag=ASSOCIATE_TAG,
              access_key_id=AWS_KEY,
              secret_access_key=AWS_SECRET_KEY)
    result = api.item_lookup(asin, ResponseGroup='ItemAttributes, OfferFull, Images')
    item = result.Items.Item[0]

    title = item.ItemAttributes.Title
    url = item.DetailPageURL

    if item.OfferSummary:
        amount = (item.OfferSummary.LowestNewPrice.Amount / 100)
    elif item.ItemAttributes.ListPrice:
        amount = (item.ItemAttributes.ListPrice.Amount / 100)
    else:
        amount = 0.0

    image_url = item.LargeImage.URL

    wish = Wish(
        user=user,
        asin=asin,
        title=title,
        amount=amount,
        is_credit=False,
        url=url,
        image_url=image_url
    )
    wish.save()

    return wish
开发者ID:averymanderson,项目名称:OysterWebApp,代码行数:41,代码来源:models.py

示例14: Crawler

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
class Crawler():
    def __init__(self):
        self.parseConfigFile()

    asinTxtPath = ''
    locales = []
    feedPath = ''

    api = ''

    log = logger.createLogger("AmazonLogger", "Amazon")

    def parseConfigFile(self):
        parser = SafeConfigParser()
        parser.read('C:/BorderSoftware/Boris/settings/boris.ini')
        self.asinTxtPath = parser.get('Amazon', 'asintxtpath')
        self.locales = parser.get('Amazon', 'locales').split(',')
        self.feedPath = parser.get('Amazon', 'feedpath')

    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)

    # This procedure loads products from the .txt file corresponding with the locale.
    def loadProducts(self, locale):
        f = open(self.asinTxtPath + locale + '.txt')
        products = f.read().splitlines()
        f.close()

        return products

    # This procedure makes the API call and retrieves all necessary data from the response
    def gatherData(self, ASIN, locale):
        productData = dict()

        tries = 0
        while True:
            try:
                result = self.api.item_lookup(ASIN, ResponseGroup='Large')
                break
            except InvalidParameterValue:  # ID doesn't exist for this locale
                return
            except AWSError:  # Product not accessible through API
                self.log.info('Not accessible through API: ' + ASIN + ' - Locale: ' + locale)
                return
            except Exception as e:
                print 'Amazon timed out'
                print e
                tries += 1
                time.sleep(7)

                if tries == 20:
                    return

        for item in result.Items.Item:
            productData["asin"] = item.ASIN.text
            productData["deep_link"] = item.DetailPageURL.text
            productData["image_large"] = item.ImageSets.ImageSet.LargeImage.URL.text
            productData["image_medium"] = item.ImageSets.ImageSet.MediumImage.URL.text
            productData["image_small"] = item.ImageSets.ImageSet.SmallImage.URL.text
            productData["ean"] = item.ItemAttributes.EAN.text
            productData["category"] = item.ItemAttributes.Binding.text
            productData["title"] = item.ItemAttributes.Title.text
            try:
                productData["currency"] = item.Offers.Offer.OfferListing.Price.CurrencyCode.text
            except AttributeError:
                self.log.info("No offer data available for: " + ASIN + ' - Locale: ' + locale)
                break
            productData["price"] = item.Offers.Offer.OfferListing.Price.FormattedPrice.text

            try:
                productData["color"] = item.ItemAttributes.Color.text
            except AttributeError:  # Some locales don't contain color.
                productData["color"] = ''
            try:
                productData["brand"] = item.ItemAttributes.Brand.text
            except AttributeError:  # Some products, like dvd's, don't have a brand.
                productData["brand"] = ''
#.........这里部分代码省略.........
开发者ID:Borderloop,项目名称:Nutella,代码行数:103,代码来源:Amazon.py

示例15: __init__

# 需要导入模块: from amazonproduct import API [as 别名]
# 或者: from amazonproduct.API import item_lookup [as 别名]
class CWMovieCollectionParsingManager:
	
	def __init__(self):
		self.api = API(locale='de')

	def initAmazonApi(self, ean):
		self.amazon = self.api.item_lookup(ItemId=ean, IdType='EAN', SearchIndex='All', ResponseGroup='Large').Items.Item

	def initOfdbApi(self, ean):
		xmlUrl = 'http://ofdbgw.geeksphere.de/searchean/'+ean
		self.ofdb = ET.parse(urllib.urlopen(xmlUrl)).getroot()
		xmlUrl = 'http://ofdbgw.home-of-root.de/movie/'+self.ofdb.findall('resultat')[0].findall('eintrag')[0].findall('filmid')[0].text
		self.ofdb = ET.parse(urllib.urlopen(xmlUrl)).getroot()

	def Parse(self, ean):		
		self.initAmazonApi(ean)
		self.initOfdbApi(ean)

		MCItem = CWMovieCollectionItem()
		MCItem.ean = ean
		MCItem.actors = self.GetActors()
		MCItem.directors = self.GetDirectors()
		MCItem.manufacturer = self.GetManufacturer()
		MCItem.productGroup = self.GetProductGroup()
		MCItem.title = self.GetTitle()
		MCItem.price = self.GetPrice()
		MCItem.amazonUrl = self.GetAmazonUrl()
		MCItem.asin = self.GetAsin()
		MCItem.studio = self.GetStudio()
		MCItem.audienceRating = self.GetAudienceRating()
		MCItem.imageUrl = self.GetImageUrl(MCItem.asin)
		MCItem.summary = self.GetSummary()
		MCItem.languages = self.GetLanguage()
		MCItem.subtitles = self.GetSubtitles()
		MCItem.audioFormats = self.GetAudioFormat()
		MCItem.publicationDate = self.GetPublicationDate()
		MCItem.runningTime = self.GetRunningTime()
		MCItem.rating = CWMovieCollectionRating(MCItem.title,  self.GetOfdbStars())
		MCItem.rental.append(CWMovieCollectionRental())

		return MCItem

	def GetOfdbStars(self):
		ofdbStars = ''
		try:
			ofdbStars =  self.ofdb.findall('resultat')[0].findall('bewertung')[0].findall('note')[0].text
		except:
			if DEBUG == True:
				print 'Error parsing ofdbstars'
				print sys.exc_info()
		return ofdbStars

	def GetRunningTime(self):
		runningTime = ''
		try:
			runningTime = str(self.amazon.ItemAttributes.RunningTime)
		except:
			if DEBUG == True:
				print 'Error parsing runningtime'
				print sys.exc_info()
		return runningTime
	
	def GetPublicationDate(self):
		publicationDate = ''
		try:
			publicationDate = str(self.amazon.ItemAttributes.PublicationDate)
		except:
			if DEBUG == True:
				print 'Error parsing publicationdate'
				print sys.exc_info()
		return publicationDate

	def GetAudioFormat(self):
		audioFormats = []
		try:
			for audioFormat in self.amazon.ItemAttributes.Languages.Language:
				try:
					audioFormats.append(str(audioFormat.AudioFormat))
				except:
					if DEBUG == True:
						print 'No audio format found'
		except:
			if DEBUG == True:
				print 'Error parsing audioformat'
				print sys.exc_info()
		return audioFormats

	def GetSubtitles(self):
		subtitles = []
		try:
			for subtitle in self.amazon.ItemAttributes.Languages.Language:
				if subtitle.Type == 'Subtitled':
					subtitles.append(str(subtitle.Name))
		except:
			if DEBUG == True:
				print 'Error parsing subtitle'
				print sys.exc_info()
		return subtitles

	def GetLanguage(self):
#.........这里部分代码省略.........
开发者ID:Thiedze,项目名称:CWMovieCollection,代码行数:103,代码来源:CWMovieCollectionParsingManager.py


注:本文中的amazonproduct.API.item_lookup方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。