我真的被这个困住了!我从 Amazon 获取了一些产品数据,这些数据以 XML 形式返回。当搜索关键字有效时,它返回带有节点Items
>的 XML Item
。使用错误的关键字,或不返回有效结果的关键字,Item
节点不存在。我正在使用一些函数将此 XML 转换为 Object 以便于解析。然后用于hasattr
递归检查各个节点。
data = someXMLConverter(xml)
#works
if hasattr(data, 'Items'):
#doesn't work
if hasattr(data.Items, 'Item'):
#some processing here
else:
return 'Error'
else:
return 'Error'
即使Item
节点不存在,也hasattr
返回 true。因此,如果出现错误,我的网站就会爆炸!
有任何想法吗?
示例 XML:
<ItemSearchResponse>
<OperationRequest>
<HTTPHeaders><Header Name="UserAgent" Value="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"/></HTTPHeaders>
<RequestId>a393e9db-b86e-41de-965d-922c947056ff</RequestId>
<Arguments>
<Argument Name="Operation" Value="ItemSearch"/>
<Argument Name="Service" Value="AWSECommerceService"/>
<Argument Name="Signature" Value="z/R9HjzqukC6J53bmF4LPxh/xtlwBv9k+u6QjGsgFmA="/>
<Argument Name="ItemPage" Value="1"/>
<Argument Name="AssociateTag" Value="rutwsblog-20"/>
<Argument Name="Version" Value="2006-09-11"/>
<Argument Name="Keywords" Value="dggd"/>
<Argument Name="AWSAccessKeyId" Value="AKIAJ3TAUM7ANQFQYP7Q"/>
<Argument Name="Timestamp" Value="2013-05-17T16:50:55"/>
<Argument Name="ResponseGroup" Value="Medium"/>
<Argument Name="SearchIndex" Value="Books"/>
</Arguments>
<RequestProcessingTime>0.0217790000000000</RequestProcessingTime>
</OperationRequest>
<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<ItemPage>1</ItemPage>
<Keywords>dggd</Keywords>
<ResponseGroup>Medium</ResponseGroup>
<SearchIndex>Books</SearchIndex>
</ItemSearchRequest>
<Errors>
<Error>
<Code>AWS.ECommerceService.NoExactMatches</Code>
<Message>We did not find any matches for your request.</Message>
</Error>
</Errors>
</Request>
<TotalResults>0</TotalResults>
<TotalPages>0</TotalPages>
<MoreSearchResultsUrl>http://www.amazon.com/gp/redirect.html?camp=2025&creative=386001&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fsearch%3Fkeywords%3Ddggd%26url%3Dsearch-alias%253Dstripbooks&linkCode=xm2&tag=xxxx-20&SubscriptionId=xxxx</MoreSearchResultsUrl>
</Items>
</ItemSearchResponse>