无法访问XML

时间:2016-02-03 18:34:33

标签: python xml

我试图将XML格式的字符串解析为一些普通的python对象,我尝试使用findfindall方法来访问某些子元素,但它不起作用。

以下是我试图解析的XML数据:

<?xml version="1.0" ?>
<ItemSearchResponse
    xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">

    <Items>
        <Request>
            <IsValid>True</IsValid>
            <ItemSearchRequest>
                <Keywords>iphone</Keywords>
                <ResponseGroup>ItemAttributes</ResponseGroup>
                <SearchIndex>All</SearchIndex>
            </ItemSearchRequest>
        </Request>
        <TotalResults>40721440</TotalResults>
        <TotalPages>4072144</TotalPages>

        <Item>
            <ASIN>B00YV50QU4</ASIN>
            <ParentASIN>B018GTHAKO</ParentASIN>
            <DetailPageURL>http://www.amazon.com/Apple-iPhone-MD439LL-Smartphone-Refurbished/dp/B00YV50QU4%3Fpsc%3D1%26SubscriptionId%3DAKIAIEEA4BKMTHTI2T7A%26tag%3Dshopit021-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00YV50QU4</DetailPageURL>
            <ItemLinks>

            </ItemLinks>
            <ItemAttributes>
            </ItemAttributes>
        </Item>
        <Item>
            <ASIN>B00VHSXBUA</ASIN>
            <ParentASIN>B0152TROY8</ParentASIN>
            <ItemAttributes>
            </ItemAttributes>
        </Item>
    </Items>
</ItemSearchResponse>

我删除了一些数据,以便缩短这个样本。

这是我的代码。

data  = et.fromstring(response)
            items = data[0][3]
            print items.tag
            items = data[0].findall('item')
            print len(items.findall('.//item'))

访问子节点('item')的第一种方法是使用列表索引表示法,它工作正常。但是使用find all方法它不起作用,len()总是返回0。

我尝试过使用XPath和其他方法,但使用索引是让它工作的唯一方法。

为什么像findfindall这样的方法不起作用?

1 个答案:

答案 0 :(得分:1)

  

为什么像find和findall这样的方法不起作用?

因为没有名为Item的元素。您的文档定义了http://webservices.amazon.com/AWSECommerceService/2011-08-01的默认XML名称空间,这意味着文档中看起来像<Item>的元素实际上包含在该名称空间中,并且与元素中的不同在没有默认XML命名空间(或使用不同的XML命名空间)的文档中看起来像<Item>

你想要这样的东西:

>>> ns = 'http://webservices.amazon.com/AWSECommerceService/2011-08-01'
>>> items = data[0].findall('{%s}Item' % ns)
>>> items
[<Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba8c0>, <Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba680>]

或者,使用XPath:

>>> items = data[0].xpath('n:Item', namespaces={'n': ns})
>>> items
[<Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba8c0>, <Element {http://webservices.amazon.com/AWSECommerceService/2011-08-01}Item at 0x7f1cbaaba680>]
相关问题