方法'hasattr'没有正确测试属性?

时间:2013-05-17 17:13:45

标签: python python-2.7 xml-parsing hasattr

我真的很难受!我从亚马逊获得了一些产品数据,它以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>

1 个答案:

答案 0 :(得分:2)

您可以使用以下内容避免在获得None

时进行处理
data = someXMLConverter(xml)

if hasattr(data, 'Items'):
    if hasattr(data.Items, 'Item') and data.Items.Item is not None:
        #some processing here
    else:
        return 'Error'
else:
    return 'Error'

如果hasattr返回False,if语句会被短路,我们可以安全地检查None