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


Python AmazonAPI.search方法代码示例

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


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

示例1: __init__

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class Amazon:
    def __init__(self):
        self.amazon = AmazonAPI('AKIAJTMXQEFQVV7SEF5Q', 'CwNQ/cKQNXckNMhfb7oQ0KTmBoaJNPqSFqzKtubf',
                                'fbhackcom0d-21', region='UK')

    def search_for(self, text, top=3):
        try:
            products = self.amazon.search(Keywords=text, SearchIndex='All')

            top_products = []

            product_titles = {}

            for product in products:
                if product.title is not None and product.price_and_currency is not None:
                    title = product.title
                    # if len(title) > 50:
                    #     title = title[:50] + "..."

                    product_titles[product.offer_url] = title
                    top_products.append({
                        'offer_url': product.offer_url,
                        'name': product.title,
                        'image': product.medium_image_url,
                        'price': product.price_and_currency[0],
                        'currency': product.price_and_currency[1],
                    })
                    top -= 1
                    if top == 0:
                        break

            return top_products
        except:
            return []
开发者ID:jhirniak,项目名称:pinkunicorns,代码行数:36,代码来源:shopping.py

示例2: AmazonScraper

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class AmazonScraper(object):
    def __init__(self, access_key, secret_key, associate_tag, *args, **kwargs):
        self.api = AmazonAPI(access_key, secret_key, associate_tag, *args, **kwargs)

    def reviews(self, ItemId=None, URL=None):
        return Reviews(self, ItemId, URL)

    def review(self, Id=None, URL=None):
        return Review(self, Id, URL)

    def lookup(self, URL=None, **kwargs):
        if URL:
            kwargs['ItemId'] = extract_asin(URL)

        result = self.api.lookup(**kwargs)
        if isinstance(result, (list, tuple)):
            result = [Product(p) for p in result]
        else:
            result = Product(result)
        return result

    def similarity_lookup(self, **kwargs):
        for p in self.api.similarity_lookup(**kwargs):
            yield Product(p)

    def browse_node_lookup(self, **kwargs):
        return self.api.browse_node_lookup(**kwargs)

    def search(self, **kwargs):
        for p in self.api.search(**kwargs):
            yield Product(p)

    def search_n(self, n, **kwargs):
        for p in self.api.search_n(n, **kwargs):
            yield Product(p)
开发者ID:kinglouisxviii,项目名称:amazon_scraper,代码行数:37,代码来源:__init__.py

示例3: app_results

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
def app_results(query):
    amazon = AmazonAPI(AWS_KEY, SECRET_KEY, ASSOC_TAG)
    products = amazon.search(Keywords=query, SearchIndex='All')
    if referrer == 'dashboard':
        return render_template("amazon_bottlenose2.html", products = products)
    else:
        form = AddProductForm()
        return render_template("amazon_bottlenose_add.html", products = products, form=form)
开发者ID:tatertot,项目名称:lendinglibrary,代码行数:10,代码来源:borrow.py

示例4: getTopProductIDs

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
def getTopProductIDs(keywords="camera", searchIndex='Electronics'):
	AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG = \
	getAmazomConfidentialKeys()

	amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)
	products = amazon.search(Keywords=keywords, SearchIndex=searchIndex)

	productIDs = []
	for i, product in enumerate(products):
		productIDs.append(product.asin)

	return productIDs
开发者ID:KEHANG,项目名称:Smart_Review_Summarization,代码行数:14,代码来源:regular_scraping.py

示例5: test_search_amazon_uk

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
    def test_search_amazon_uk(self):
        """Test Poduct Search on Amazon UK.

        Tests that a product search on Amazon UK is working and that the
        currency of any of the returned products is GBP. The test fails if no
        results were returned.
        """
        amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG, region="UK")
        assert_equals(amazon.api.Region, "UK", "Region has not been set to UK")

        products = amazon.search(Keywords="Kindle", SearchIndex="All")
        currencies = [product.price_and_currency[1] for product in products]
        assert_true(len(currencies), "No products found")

        is_gbp = "GBP" in currencies
        assert_true(is_gbp, "Currency is not GBP, cannot be Amazon UK, though")
开发者ID:philfreo,项目名称:python-amazon-simple-product-api,代码行数:18,代码来源:tests.py

示例6: run

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
def run():

    b = books()
    amazon = AmazonAPI(settings.AMZ, settings.AMZSCRT, settings.AMZID)
    query = amazon.search(Keywords='free kindle books', SearchIndex = 'KindleStore')




    for i in query:

        #new = books.objects.get(id=i.asin)
        b = books()

        #if book exists update the price and the update timestamp

        try:

            q = books.objects.get(id=i.asin)
            #if len(new) > 0:
            if i.price_and_currency[0] != None:
                q.price = i.price_and_currency[0]
            q.save()

        except:


            b.id=(i.asin)
            b.title = (i.title)
            b.description = (i.editorial_review)
            b.image = (i.large_image_url)
            b.author = (i.author)
            b.number_pages = (i.pages)
            b.publisher = (i.publisher)
            b.price = 'Free'
            b.url = (i.offer_url)
            b.reviews = (i.reviews[1])
            b.slug = create_slug(b)

            b.save()
开发者ID:rschmidtz,项目名称:booklos-dev,代码行数:42,代码来源:callApi.py

示例7: TestAmazonApi

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class TestAmazonApi(TestCase):
    """Test Amazon API

    Test Class for Amazon simple API wrapper.
    """
    def setUp(self):
        """Set Up.

        Initialize the Amazon API wrapper. The following values:

        * AMAZON_ACCESS_KEY
        * AMAZON_SECRET_KEY
        * AMAZON_ASSOC_TAG

        Are imported from a custom file named: 'test_settings.py'
        """
        self.amazon = AmazonAPI(
            AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)

    def test_lookup(self):
        """Test Product Lookup.

        Tests that a product lookup for a kindle returns results and that the
        main methods are working.
        """
        product = self.amazon.lookup(ItemId="B007HCCNJU")
        assert_true('Kindle' in product.title)
        assert_equals(product.ean, '0814916017775')
        assert_equals(
            product.large_image_url,
            'http://ecx.images-amazon.com/images/I/41VZlVs8agL.jpg'
        )
        assert_equals(
            product.get_attribute('Publisher'),
            'Amazon'
        )
        assert_equals(product.get_attributes(
            ['ItemDimensions.Width', 'ItemDimensions.Height']),
            {'ItemDimensions.Width': '650', 'ItemDimensions.Height': '130'})
        assert_true(len(product.browse_nodes) > 0)
        assert_true(product.price_and_currency[0] is not None)
        assert_true(product.price_and_currency[1] is not None)
        assert_equals(product.browse_nodes[0].id, 2642129011)
        assert_equals(product.browse_nodes[0].name, 'eBook Readers')

    def test_batch_lookup(self):
        """Test Batch Product Lookup.

        Tests that a batch product lookup request returns multiple results.
        """
        asins = ['B00AWH595M', 'B007HCCNJU', 'B00BWYQ9YE',
                 'B00BWYRF7E', 'B00D2KJDXA']
        products = self.amazon.lookup(ItemId=','.join(asins))
        assert_equals(len(products), 5)
        for i, product in enumerate(products):
            assert_equals(asins[i], product.asin)

    def test_search(self):
        """Test Product Search.

        Tests that a product search is working (by testing that results are
        returned). And that each result has a title attribute. The test
        fails if no results where returned.
        """
        products = self.amazon.search(Keywords='kindle', SearchIndex='All')
        for product in products:
            assert_true(hasattr(product, 'title'))
            break
        else:
            assert_true(False, 'No search results returned.')

    def test_search_n(self):
        """Test Product Search N.

        Tests that a product search n is working by testing that N results are
        returned.
        """
        products = self.amazon.search_n(
            1,
            Keywords='kindle',
            SearchIndex='All'
        )
        assert_equals(len(products), 1)

    def test_amazon_api_defaults_to_US(self):
        """Test Amazon API defaults to the US store."""
        amazon = AmazonAPI(
            AMAZON_ACCESS_KEY,
            AMAZON_SECRET_KEY,
            AMAZON_ASSOC_TAG
        )
        assert_equals(amazon.api.Region, "US")

    def test_search_amazon_uk(self):
        """Test Poduct Search on Amazon UK.

        Tests that a product search on Amazon UK is working and that the
        currency of any of the returned products is GBP. The test fails if no
        results were returned.
        """
#.........这里部分代码省略.........
开发者ID:Mondego,项目名称:pyreco,代码行数:103,代码来源:allPythonContent.py

示例8: TestAmazonApi

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class TestAmazonApi(TestCase):
    """Test Amazon API

    Test Class for Amazon simple API wrapper.
    """
    def setUp(self):
        """Set Up.

        Initialize the Amazon API wrapper. The following values:

        * AMAZON_ACCESS_KEY
        * AMAZON_SECRET_KEY
        * AMAZON_ASSOC_TAG

        Are imported from a custom file named: 'test_settings.py'
        """
        self.amazon = AmazonAPI(AMAZON_ACCESS_KEY,
            AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)

    def test_lookup(self):
        """Test Product Lookup.

        Tests that a product lookup for a kindle returns results and that the
        main methods are working.
        """
        product = self.amazon.lookup(ItemId="B0051QVF7A")
        assert_equals(product.title,
            'Kindle, Wi-Fi, 6" E Ink Display - for international shipment')
        assert_equals(product.price_and_currency, (109.0, 'USD'))
        assert_equals(product.ean, '0814916014354')
        assert_equals(product.large_image_url,
            'http://ecx.images-amazon.com/images/I/411H%2B731ZzL.jpg')
        assert_equals(product.get_attribute('Publisher'),
            'Amazon Digital Services, Inc')
        assert_equals(product.get_attributes(
            ['ItemDimensions.Width', 'ItemDimensions.Height']),
            {'ItemDimensions.Width': '450', 'ItemDimensions.Height': '34'})

    def test_batch_lookup(self):
        """Test Batch Product Lookup.

        Tests that a batch product lookup request returns multiple results.
        """
        asins = ['B0051QVESA', 'B005DOK8NW', 'B005890G8Y',
                 'B0051VVOB2', 'B005890G8O']
        products = self.amazon.lookup(ItemId=','.join(asins))
        assert_equals(len(products), 5)
        for i, product in enumerate(products):
            assert_equals(asins[i], product.asin)

    def test_search(self):
        """Test Product Search.

        Tests that a product search is working (by testing that results are
        returned). And that each result has a title attribute. The test
        fails if no results where returned.
        """
        products = self.amazon.search(Keywords='kindle', SearchIndex='All')
        for product in products:
            assert_true(hasattr(product, 'title'))
            break
        else:
            assert_true(False, 'No search results returned.')

    def test_search_n(self):
        """Test Product Search N.

        Tests that a product search n is working by testing that N results are
        returned.
        """
        products = self.amazon.search_n(1, Keywords='kindle',
            SearchIndex='All')
        assert_equals(len(products), 1)

    def test_amazon_api_defaults_to_US(self):
        """Test Amazon API defaults to the US store."""
        amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY,
            AMAZON_ASSOC_TAG)
        assert_equals(amazon.api.Region, "US")

    def test_search_amazon_uk(self):
        """Test Poduct Search on Amazon UK.
        
        Tests that a product search on Amazon UK is working and that the
        currency of any of the returned products is GBP. The test fails if no
        results were returned.
        """
        amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY,
            AMAZON_ASSOC_TAG, region="UK")
        assert_equals(amazon.api.Region, "UK", "Region has not been set to UK")

        products = amazon.search(Keywords='Kindle', SearchIndex='All')
        currencies = [product.price_and_currency[1] for product in products]
        assert_true(len(currencies), "No products found")

        is_gbp = 'GBP' in currencies
        assert_true(is_gbp, "Currency is not GBP, cannot be Amazon UK, though")
开发者ID:jamespacileo,项目名称:python-amazon-simple-product-api,代码行数:99,代码来源:tests.py

示例9: Amazon

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class Amazon(object):

    def __init__(self):
        try:
            self.connection = AmazonAPI(
                settings.AMAZON_ACCESS_KEY, settings.AMAZON_SECRET_KEY,
                settings.AMAZON_ASSOCIATE_TAG
            )
            logger.info(u'Established Amazon API connection')
        except:
            self.connection = None
            logger.error(traceback.format_exc())
            logger.error(u'Failed to establish Amazon API connection')
        self.total_count = 0

    def get_review_count(self, title, url, has_review, review_url):
        if not has_review:
            return 0
        try:
            response = requests.get(review_url)
            soup = BeautifulSoup(response.content, 'html.parser')
            count = soup.find(string=re.compile('[0-9,]+ customer reviews'))
            count = int(count.split()[0].replace(',', ''))
            logger.info(
                u'Review count for Amazon item {} from url {} is {}'.format(
                    title, url, count
                )
            )
            return count
        except AttributeError:
            logger.warning(
                u'Review count for Amazon item {} from url {} not foun'
                'd'.format(title, url)
                )
            return 0
        except:
            logger.error(traceback.format_exc())
            return 0

    def get_image_list(self, result):
        image_list = []
        for url in [str(image.LargeImage.URL) for image in result.images]:
            response = requests.get(url)
            image = Image.open(BytesIO(response.content))
            height, width = image.size
            if height >= 500 and width >= 500:
                image_list.append(url)
        logger.info(
            u'Got {} images for Amazon item {}'.format(
                len(image_list), result.title
            )
        )
        return json.dumps(image_list)

    def parse_result(self, result, search_obj):
        url = '/'.join(result.offer_url.split('/')[:-1])
        title = result.title
        feature_list = json.dumps(result.features)
        image_list = self.get_image_list(result)
        price = result.price_and_currency[0] or result.list_price[0] or 0
        manufacturer = result.manufacturer
        mpn = result.mpn
        review_count = self.get_review_count(title, url, *result.reviews)
        item = {
            'search': search_obj,
            'url': url,
            'title': title,
            'feature_list': feature_list,
            'image_list': image_list,
            'price': price,
            'manufacturer': manufacturer,
            'mpn': mpn,
            'review_count': review_count,
        }
        message = 'Parsed Amazon item:\n'
        for key, value in item.items():
            message += '{}: {}\n'.format(key.upper(), value)
        logger.info(message.strip())
        return item

    def search(self, search_obj):
        try:
            results = self.connection.search(
                Keywords=search_obj.query, SearchIndex='All'
            )
            results = list(reversed(list(results)))
            logger.info(
                u'Got {} search results from Amazon API for query {}'.format(
                    len(results), search_obj.query
                )
            )
        except:
            results = []
            logger.error(traceback.format_exc())
            logger.warning(
                u'Got 0 search results from Amazon API for query {}'.format(
                    search_obj.query
                )
            )
        search_obj.date_searched = timezone.now()
#.........这里部分代码省略.........
开发者ID:tishmen,项目名称:amazon_ebay,代码行数:103,代码来源:utils.py

示例10: TestAmazonApi

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class TestAmazonApi(unittest.TestCase):
    """Test Amazon API

    Test Class for Amazon simple API wrapper.
    """

    def setUp(self):
        """Set Up.

        Initialize the Amazon API wrapper. The following values:

        * AMAZON_ACCESS_KEY
        * AMAZON_SECRET_KEY
        * AMAZON_ASSOC_TAG

        Are imported from a custom file named: 'test_settings.py'
        """
        self.amazon = AmazonAPI(
            AMAZON_ACCESS_KEY,
            AMAZON_SECRET_KEY,
            AMAZON_ASSOC_TAG,
            CacheReader=cache_reader,
            CacheWriter=cache_writer,
            MaxQPS=0.5
        )

    def test_lookup(self):
        """Test Product Lookup.

        Tests that a product lookup for a kindle returns results and that the
        main methods are working.
        """
        product = self.amazon.lookup(ItemId="B00I15SB16")
        assert_true('Kindle' in product.title)
        assert_equals(product.ean, '0848719039726')
        assert_equals(
            product.large_image_url,
            'http://ecx.images-amazon.com/images/I/51XGerXeYeL.jpg'
        )
        assert_equals(
            product.get_attribute('Publisher'),
            'Amazon'
        )
        assert_equals(product.get_attributes(
            ['ItemDimensions.Width', 'ItemDimensions.Height']),
            {'ItemDimensions.Width': '469', 'ItemDimensions.Height': '40'})
        assert_true(len(product.browse_nodes) > 0)
        assert_true(product.price_and_currency[0] is not None)
        assert_true(product.price_and_currency[1] is not None)
        assert_equals(product.browse_nodes[0].id, 2642129011)
        assert_equals(product.browse_nodes[0].name, 'eBook Readers')

    def test_lookup_nonexistent_asin(self):
        """Test Product Lookup with a nonexistent ASIN.

        Tests that a product lookup for a nonexistent ASIN raises AsinNotFound.
        """
        assert_raises(AsinNotFound, self.amazon.lookup, ItemId="ABCD1234")

    def test_bulk_lookup(self):
        """Test Baulk Product Lookup.

        Tests that a bulk product lookup request returns multiple results.
        """
        asins = [TEST_ASIN, 'B00BWYQ9YE',
                 'B00BWYRF7E', 'B00D2KJDXA']
        products = self.amazon.lookup(ItemId=','.join(asins))
        assert_equals(len(products), len(asins))
        for i, product in enumerate(products):
            assert_equals(asins[i], product.asin)

    def test_lookup_bulk(self):
        """Test Bulk Product Lookup.

        Tests that a bulk product lookup request returns multiple results.
        """
        asins = [TEST_ASIN, 'B00BWYQ9YE',
                 'B00BWYRF7E', 'B00D2KJDXA']
        products = self.amazon.lookup_bulk(ItemId=','.join(asins))
        assert_equals(len(products), len(asins))
        for i, product in enumerate(products):
            assert_equals(asins[i], product.asin)

    def test_lookup_bulk_empty(self):
        """Test Bulk Product Lookup With No Results.

        Tests that a bulk product lookup request with no results
        returns an empty list.
        """
        asins = ['not-an-asin', 'als-not-an-asin']
        products = self.amazon.lookup_bulk(ItemId=','.join(asins))
        assert_equals(type(products), list)
        assert_equals(len(products), 0)

    def test_search(self):
        """Test Product Search.

        Tests that a product search is working (by testing that results are
        returned). And that each result has a title attribute. The test
        fails if no results where returned.
#.........这里部分代码省略.........
开发者ID:fadedblue,项目名称:python-amazon-simple-product-api,代码行数:103,代码来源:tests.py

示例11: open

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
from amazon.api import AmazonAPI
import json
from datetime import date

with open('amazon.config') as configfile:
    config = json.load(configfile)

amazon = AmazonAPI(str(config['AWS_ACCESS_KEY_ID']),
                   str(config['AWS_SECRET_ACCESS_KEY']),
                   str(config['AWS_ASSOCIATE_TAG']),
                   region='US')

results = amazon.search(Author='ben aaronovitch',
                        Sort='-publication_date',
                        SearchIndex='Books')

for item in results:
    if item.publication_date >= date.today():
        if item.edition != "Reprint" and item.binding == "Hardcover":
            print item.title
            print item.publication_date
            print item.offer_url
            print item.authors
            print item.isbn
    else:
        break
开发者ID:DoHe,项目名称:pybook,代码行数:28,代码来源:amazon_api_test.py

示例12: AZ

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class AZ(object):
    def __init__(self):
        init_logging()
        self.logger = logging.getLogger(__name__)
        self.logger.info("Amazon object initialized")

        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "az_config.yml"), "r") as fh:
            settings = yaml.load(fh)

        self.db = Mysql(settings['db_config'])

        self.access_key = settings['access_key_id']
        self.secret_key = settings['secret_key_id']
        self.associate_tag = settings['associate_tag']
        self.default_weight = settings['default_weight']
        self.az_price = None
        self.az_asin = None
        self.az_sales_rank = None
        self.az_url = None
        self.az_match = None

        self.amazon = AmazonAPI(self.access_key, self.secret_key, self.associate_tag)

    def destroy(self):
        self.logger.info("Database connection closed...")
        self.db.exit()
        self.logger.info("Amazon object destroyed")

    def find_best_match(self, title, cat='All'):  # TODO: consider using cat='Blended' for default
        """

        :param title: string containing the source site product title
        :param cat: string containing the category for searchindex on amazon
        :return: product dict with price, weight, sales_rank, offer_url and T if match occurred on title search,
        K if match occurred on keyword search, N if no match occurred.
        """
        self._find_by_title(title, cat)
        if self.product['az_price'] != 0:
            self.product['az_match'] = 'T'
        if self.product['az_price'] == 0:
            self._find_by_key(title, cat)
            if self.product['az_price'] != 0:
                self.product['az_match'] = 'K'
        if self.product['az_price'] == 0:  # we didn't find any match so clean remaining attrs
            (self.product['az_sales_rank'], self.product['az_match'], self.product['az_url']) = (0, 'N', '')
        self._get_attrs()
        #return self.az_price, self.az_weight, self.az_sales_rank, self.az_match, self.az_url, self.az_asin
        # consider returning a status flag

    def _find_by_title(self, title, cat):
        lowest = 0.0
        try:
            products = self.amazon.search(Title=title, SearchIndex=cat)
            for i, p in enumerate(products):
                price = p.price_and_currency[0]
                if lowest == 0.0:
                    lowest = price
                    self.product['asin'] = p.asin
                elif price < lowest:
                    lowest = price
                    self.product['asin'] = p.asin
        except Exception as e:
            self.logger.warn("%s had no match in amazon" % title)
        self.product['az_price'] = lowest

    def _find_by_key(self, title, cat):
        lowest = 0.0
        try:
            products = self.amazon.search(Keywords=title, SearchIndex=cat)
            for i, p in enumerate(products):
                price = p.price_and_currency[0]
                if lowest == 0.0:
                    lowest = price
                    self.product['asin'] = p.asin
                elif price < lowest:
                    lowest = price
                    self.product['asin'] = p.asin
        except Exception as e:
            self.logger.warn("%s had no match in amazon" % title)
        self.product['az_price'] = lowest

    def _get_attrs(self):
        (r, w, u, i) = (None, None, None, None)
        if self.product.get('asin', None) is not None:
            try:
                p = self.amazon.lookup(ItemId=self.product['asin'])
                r = int(p.sales_rank)
                i = p.images[0].LargeImage.URL.text
                w = p.get_attribute('ItemDimensions.Weight')
                u = p.offer_url
                self._get_meta_rate(p.reviews[1])
            except:
                pass
            if r is None:
                r = 0
            if i is None:
                i = ''
            if w is None:
                w = self.product['az_weight']  # this should not be in hundreth-pounds
            else:
#.........这里部分代码省略.........
开发者ID:smehan,项目名称:py-webetl,代码行数:103,代码来源:AZProdSearch.py

示例13: TestAmazonApi

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class TestAmazonApi(TestCase):
    """Test Amazon API

    Test Class for Amazon simple API wrapper.
    """
    def setUp(self):
        """Set Up.

        Initialize the Amazon API wrapper. The following values:

        * AMAZON_ACCESS_KEY
        * AMAZON_SECRET_KEY
        * AMAZON_ASSOC_TAG

        Are imported from a custom file named: 'test_settings.py'
        """
        self.amazon = AmazonAPI(
            AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)

    def test_lookup(self):
        """Test Product Lookup.

        Tests that a product lookup for a kindle returns results and that the
        main methods are working.
        """
        product = self.amazon.lookup(ItemId="B007HCCNJU")
        assert_true('Kindle' in product.title)
        assert_equals(product.ean, '0814916017775')
        assert_equals(
            product.large_image_url,
            'http://ecx.images-amazon.com/images/I/41VZlVs8agL.jpg'
        )
        assert_equals(
            product.get_attribute('Publisher'),
            'Amazon'
        )
        assert_equals(product.get_attributes(
            ['ItemDimensions.Width', 'ItemDimensions.Height']),
            {'ItemDimensions.Width': '650', 'ItemDimensions.Height': '130'})
        assert_true(len(product.browse_nodes) > 0)
        assert_true(product.price_and_currency[0] is not None)
        assert_true(product.price_and_currency[1] is not None)
        assert_equals(product.browse_nodes[0].id, 2642129011)
        assert_equals(product.browse_nodes[0].name, 'eBook Readers')

    def test_batch_lookup(self):
        """Test Batch Product Lookup.

        Tests that a batch product lookup request returns multiple results.
        """
        asins = ['B0051QVESA', 'B005DOK8NW', 'B005890G8Y',
                 'B0051VVOB2', 'B005890G8O']
        products = self.amazon.lookup(ItemId=','.join(asins))
        assert_equals(len(products), 5)
        for i, product in enumerate(products):
            assert_equals(asins[i], product.asin)

    def test_search(self):
        """Test Product Search.

        Tests that a product search is working (by testing that results are
        returned). And that each result has a title attribute. The test
        fails if no results where returned.
        """
        products = self.amazon.search(Keywords='kindle', SearchIndex='All')
        for product in products:
            assert_true(hasattr(product, 'title'))
            break
        else:
            assert_true(False, 'No search results returned.')

    def test_search_n(self):
        """Test Product Search N.

        Tests that a product search n is working by testing that N results are
        returned.
        """
        products = self.amazon.search_n(
            1,
            Keywords='kindle',
            SearchIndex='All'
        )
        assert_equals(len(products), 1)

    def test_amazon_api_defaults_to_US(self):
        """Test Amazon API defaults to the US store."""
        amazon = AmazonAPI(
            AMAZON_ACCESS_KEY,
            AMAZON_SECRET_KEY,
            AMAZON_ASSOC_TAG
        )
        assert_equals(amazon.api.Region, "US")

    def test_search_amazon_uk(self):
        """Test Poduct Search on Amazon UK.

        Tests that a product search on Amazon UK is working and that the
        currency of any of the returned products is GBP. The test fails if no
        results were returned.
        """
#.........这里部分代码省略.........
开发者ID:PatrickSocha,项目名称:python-amazon-simple-product-api,代码行数:103,代码来源:tests.py

示例14: TestAmazonApi

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class TestAmazonApi(TestCase):
    """Test Amazon API

    Test Class for Amazon simple API wrapper.
    """

    def setUp(self):
        """Set Up.

        Initialize the Amazon API wrapper. The following values:

        * AMAZON_ACCESS_KEY
        * AMAZON_SECRET_KEY
        * AMAZON_ASSOC_TAG

        Are imported from a custom file named: 'test_settings.py'
        """
        self.amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)

    def test_lookup(self):
        """Test Product Lookup.

        Tests that a product lookup for a kindle returns results and that the
        main methods are working.
        """
        product = self.amazon.lookup(ItemId="B0051QVF7A")
        assert_equals(product.title, 'Kindle, Wi-Fi, 6" E Ink Display - for international shipment')
        assert_equals(product.ean, "0814916014354")
        assert_equals(product.large_image_url, "http://ecx.images-amazon.com/images/I/411H%2B731ZzL.jpg")
        assert_equals(product.get_attribute("Publisher"), "Amazon Digital Services, Inc")
        assert_equals(
            product.get_attributes(["ItemDimensions.Width", "ItemDimensions.Height"]),
            {"ItemDimensions.Width": "450", "ItemDimensions.Height": "34"},
        )
        assert_true(len(product.browse_nodes) > 0)
        assert_equals(product.browse_nodes[0].id, 2642129011)
        assert_equals(product.browse_nodes[0].name, "eBook Readers")

    def test_batch_lookup(self):
        """Test Batch Product Lookup.

        Tests that a batch product lookup request returns multiple results.
        """
        asins = ["B0051QVESA", "B005DOK8NW", "B005890G8Y", "B0051VVOB2", "B005890G8O"]
        products = self.amazon.lookup(ItemId=",".join(asins))
        assert_equals(len(products), 5)
        for i, product in enumerate(products):
            assert_equals(asins[i], product.asin)

    def test_search(self):
        """Test Product Search.

        Tests that a product search is working (by testing that results are
        returned). And that each result has a title attribute. The test
        fails if no results where returned.
        """
        products = self.amazon.search(Keywords="kindle", SearchIndex="All")
        for product in products:
            assert_true(hasattr(product, "title"))
            break
        else:
            assert_true(False, "No search results returned.")

    def test_search_n(self):
        """Test Product Search N.

        Tests that a product search n is working by testing that N results are
        returned.
        """
        products = self.amazon.search_n(1, Keywords="kindle", SearchIndex="All")
        assert_equals(len(products), 1)

    def test_amazon_api_defaults_to_US(self):
        """Test Amazon API defaults to the US store."""
        amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)
        assert_equals(amazon.api.Region, "US")

    def test_search_amazon_uk(self):
        """Test Poduct Search on Amazon UK.

        Tests that a product search on Amazon UK is working and that the
        currency of any of the returned products is GBP. The test fails if no
        results were returned.
        """
        amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG, region="UK")
        assert_equals(amazon.api.Region, "UK", "Region has not been set to UK")

        products = amazon.search(Keywords="Kindle", SearchIndex="All")
        currencies = [product.price_and_currency[1] for product in products]
        assert_true(len(currencies), "No products found")

        is_gbp = "GBP" in currencies
        assert_true(is_gbp, "Currency is not GBP, cannot be Amazon UK, though")

    def test_similarity_lookup(self):
        """Test Similarity Lookup.

        Tests that a similarity lookup for a kindle returns 10 results.
        """
        products = self.amazon.similarity_lookup(ItemId="B0051QVF7A")
#.........这里部分代码省略.........
开发者ID:philfreo,项目名称:python-amazon-simple-product-api,代码行数:103,代码来源:tests.py

示例15: Main

# 需要导入模块: from amazon.api import AmazonAPI [as 别名]
# 或者: from amazon.api.AmazonAPI import search [as 别名]
class Main(object):
    """
    A class that gives access to this test application
    """

    # The list of products obtained
    searched_products = list()
    products = None

    def __init__(self):
        self.region_options = bottlenose.api.SERVICE_DOMAINS.keys()
        # Check if we have credentials stored, if so, load them
        if os.path.isfile("amazon_credentials.json"):
            LOGGER.info("Getting Amazon credentials from stored file...")
            credentials = json.load(open("amazon_credentials.json"))
            AMAZON_ACCESS_KEY = credentials["amazon_access_key"]
            AMAZON_SECRET_KEY = credentials["amazon_secret_key"]
            AMAZON_ASSOC_TAG = credentials["amazon_assoc_tag"]
            if AMAZON_SECRET_KEY and AMAZON_ACCESS_KEY and AMAZON_ASSOC_TAG:
                LOGGER.info("Got Amazon credentials!")
                self.amazon_us = AmazonAPI(
                    str(AMAZON_ACCESS_KEY), str(AMAZON_SECRET_KEY), str(AMAZON_ASSOC_TAG), region="US"
                )
            else:
                LOGGER.error("Some mandatory Amazon credentials are empty. Aborting...")
                sys.exit()
        else:
            LOGGER.error("Could not find amazon_credentials_file.json file. Aborting...")
            sys.exit()

    def search_products_by_brand(self):
        """
        Call the search method of the Amazon API searching for products/sellers of a particular brand
        """
        while True:
            brand_id = raw_input("Please insert brand to extract product info from -> ")
            try:
                if brand_id and isinstance(brand_id, str):
                    row_counter = 1
                    self.products = self.amazon_us.search(Brand=brand_id, SearchIndex="Automotive")
                    """pages = self.products.iterate_pages()
                    i = 1
                    for page in pages:
                        for product in page.Items:
                            print "{0}. '{1}'".format(i, product.title)
                            i += 1
                            sleep(0.9)
                    for i, product in enumerate(self.products):
                        print "{0}. '{1}'".format(i, product.title)
                        sleep(0.9)
                    return"""
                    excel_book = self.create_brand_excel_file(brand_id, "products")
                    index = excel_book.get_active_sheet()
                    sheet = excel_book.get_sheet(index)
                    for i, product in enumerate(self.products):
                        print "{0}. '{1}'".format(i, product.title)
                        product_url = product.offer_url
                        final = product_url.rsplit("/", 1)
                        if product_url:
                            try:
                                # Write a line in excel file
                                sheet.write(row_counter, 0, brand_id)
                                sheet.write(row_counter, 1, product.asin)
                                sheet.write(row_counter, 2, product.editorial_review)
                                sheet.write(row_counter, 3, product.label)
                                sheet.write(row_counter, 4, str(product.list_price))
                                sheet.write(row_counter, 5, product.manufacturer)
                                sheet.write(row_counter, 6, product.mpn)
                                sheet.write(row_counter, 7, product.offer_url)
                                sheet.write(row_counter, 8, product.part_number)
                                sheet.write(row_counter, 9, str(product.price_and_currency))
                                sheet.write(row_counter, 10, product.publisher)
                                sheet.write(row_counter, 11, product.sales_rank)
                                sheet.write(row_counter, 12, product.sku)
                                sheet.write(row_counter, 13, product.title)

                                # Get the ASIN
                                if product.item.ASIN:
                                    sheet.write(row_counter, 15, str(product.item.ASIN))
                                else:
                                    sheet.write(row_counter, 15, "Unknown")

                                # Get the Images from the Item
                                images_urls = []
                                if product.large_image_url:
                                    images_urls.append(product.large_image_url)
                                try:
                                    image_sets = product.item.ImageSets
                                    for image_set in image_sets:
                                        if image_set.ImageSet.LargeImage.URL:
                                            images_urls.append(str(image_set.ImageSet.LargeImage.URL))
                                    images = ", ".join(x for x in images_urls)
                                    sheet.write(row_counter, 16, images)
                                except AttributeError as e:
                                    print e.message
                                    sheet.write(row_counter, 16, "Unknown")

                                # Get the model
                                if product.model:
                                    sheet.write(row_counter, 17, str(product.model))
#.........这里部分代码省略.........
开发者ID:internetmosquito,项目名称:amazon_product_searcher,代码行数:103,代码来源:main.py


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