2017-09-18 54 views
2

API我使用:https://pypi.python.org/pypi/python-amazon-simple-product-api如何捕捉在Python這個特定的異常 - amazon.api

我有我的代碼

from amazon.api import AmazonAPI 
products = self.amazon_api.search_n(1, Keywords=item['upc'], SearchIndex='All') 

例外,我得到了

SearchException: Amazon Search Error: 'AWS.ECommerceService.NoExactMatches', 'We did not find any matches for your request.' 

我這部分嘗試像這樣捕獲它

try: 
    products = self.amazon_api.search_n(1, Keywords=item['upc'], SearchIndex='All') 
    found_match = True 
except SearchException: 
    logging.warning("No search result found on Amazon for UPC: %s"%(item['upc'])) 
    found_match = False 

但我得到

NameError: global name 'SearchException' is not defined 

然後,我在我的腳本

from AWS.ECommerceService.NoExactMatches import SearchException 

開始這樣做,但後來我得到這個錯誤

ImportError: No module named AWS.ECommerceService.NoExactMatches 

我的問題是怎麼做的我默默的抓住這個具體SearchException異常?

回答

5

試試這個:

from amazon.api import AmazonAPI, SearchException 

之後,

try: 
    products = self.amazon_api.search_n(1, Keywords=item['upc'], SearchIndex='All') 
    found_match = True 
except SearchException: 
    logging.warning("No search result found on Amazon for UPC: %s"%(item['upc'])) 
    found_match = False 

應該按預期工作。

Docs可以找到here

-1

嘗試NoExactMatches例外:

from AWS.EcommerceServiec import NoExactMatches 

try: 
    products = self.amazon_api.search_n(1, Keywords=item['upc'], 
SearchIndex='All') 
    found_match = True 
except NoExactMatches: 
    logging.warning("No search result found on Amazon for UPC: %s"%(item['upc'])) 
    found_match = False 
+0

另外,現代的IDE(至少PyCharm - 絕對)允許您通過只輸入類/方法/異常/恆等,並按下Alt的名義進口任何+輸入。它節省了很多時間。 –