分析MWS Boto响应时出错

2024-10-05 14:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

使用boto,可以非常容易地解析使用boto.mws.connectionlist_orders检索到的数据,并分离出特定的数据片段,例如订单号:

from boto.mws.connection import MWSConnection

merchantId = 'XXXXXXXXXXX' 
marketplaceId = 'XXXXXXXXXXX' 
accessKeyId = 'XXXXXXXXXXX' 
secretKey = 'XXXXXXXXXXX' 

mws = MWSConnection(accessKeyId, secretKey, Merchant=merchantId) 

# ListMatchingProducts
a = mws.list_orders(CreatedAfter='2018-05-24T12:00:00Z', MarketplaceId = [marketplaceId])
# retrieve order number within parsed response
a_orderid = a.ListOrdersResult.Orders.Order[0].AmazonOrderId
print(a_orderid)

输出亚马逊订单号:

^{pr2}$

相反,如果要使用get_matching_product_for_id操作解析和隔离特定数据,那么假设要为特定的EAN产品ID获取相应的ASIN:

# GetMatchingProductForId (retrieving product info using EAN code)
b = mws.get_matching_product_for_id(MarketplaceId=marketplaceId,IdType="EAN",IdList=["5705260045710"])
# retrieve ASIN for product within result
b_asin = b.GetMatchingProductForIdResult.Products.Product.MarketplaceASIN

将引发以下错误:

Traceback (most recent call last):
  File "C:\Users\alexa\Desktop\API_Amazon_get_matching_product_for_id.py", line 20, in <module>
    b_asin = b.GetMatchingProductForIdResult.Products.Product.MarketplaceASIN
AttributeError: 'list' object has no attribute 'Products'

有人知道为什么吗?或者有更好的方法来解析boto.mws.connection响应吗?在


Tags: 数据idforgetproductconnectioneanlist
2条回答

答案就在你的错误信息里。我已经有一段时间没有使用boto了,但是即使不运行您的示例,您也可以发现问题在这里:

b_asin = b.GetMatchingProductForIdResult.Products.Product.MarketplaceASIN

错误说明:

^{pr2}$

向后看,我们可以知道python正试图访问一个名为Products的属性,但对象是一个列表。在

所以b.GetMatchingProductForIdResult是一个列表。试试print看看你能得到什么。迭代它并打印元素或打印第一个元素的dir以查看每个元素的属性。在

print(dir(b.GetMatchingProductForIdResult[0]))

回溯是你的朋友,学会它,热爱它,活下去。在

特别是MWS:

Amazon提供了一个描述响应found here的xsd文件。这应该能告诉你你到底在处理什么。更一般地说,它描述了元素here。在

答案就如@veral_Kint指出的那样。使用上面的例子,可以通过深入树并在需要时将属性视为列表来检索ASIN。我还不太明白为什么有些属性是列表,而有些属性不是列表,但在这个阶段,快速的尝试和错误使我找到了解决方案:

b_asin = b.GetMatchingProductForIdResult[0].Products.Product[0].Identifiers.MarketplaceASIN.ASIN
print(b_asin)

相关问题 更多 >