解析 MWS Boto 响应时出错

Error When Parsing MWS Boto Response

使用 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)

输出亚马逊订单号:

123-456789-123456

相反,如果要使用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 响应?

答案在你的错误信息中。我有一段时间没有使用 boto 但甚至没有尝试 运行 你的例子你可以告诉问题在这里:

b_asin = b.GetMatchingProductForIdResult.Products.Product.MarketplaceASIN

错误说:

AttributeError: 'list' object has no attribute 'Products'

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

所以 b.GetMatchingProductForIdResult 是一个列表。尝试 printing 看看你得到了什么。迭代它并打印元素或打印第一个元素的目录以查看每个元素的属性。

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

Traceback 是您的朋友,学习它,热爱它,实践它。

现在具体到 MWS:

亚马逊提供了一个 xsd 文件来描述响应 found here. This should tell you exactly what you're dealing with. More generally it describes the elements here

正如@Verbal_Kint指出的那样,解决方案在答案中。使用上面的示例,可以通过向下挖掘树并在需要时将属性视为列表来检索 ASIN。我还没有完全弄清楚为什么有些属性是列表而有些不是,但在这个阶段,快速试验和错误使我找到了解决方案:

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