0

我正在尝试检查 django 应用程序中的某些 xml 是否具有某些元素/节点,如果不只是跳过该代码块。我正在使用 hasattr() 检查元素是否存在,如果元素不存在,它应该返回 false:

if hasattr(product.ItemAttributes, 'ListPrice') \ and hasattr(product.Offers.Offer.OfferListing, 'PercentageSaved') \ and hasattr(product.LargeImage, 'URL'):

除了在我的情况下,它会引发属性错误: AttributeError at /update_products/ no such child: {http://webservices.amazon.com/AWSECommerceService/2011-08-01}LargeImage

我不明白为什么它会抛出错误而不是仅仅返回 false 并让我跳过代码块?

4

1 回答 1

3

错误是抱怨LargeImage. 这是由这个表达式引起的:product.LargeImage. 你可能想先检查一下,或者更好的是,把它放在一个try/except块中。

于 2013-08-27T19:53:03.727 回答