简体   繁体   中英

Beautifulsoup: Soupy runny xml, single loop iterate through each item

Say you have some XML that is structured like this but could take any shape using these tag with the same tag names deeper and may be reused in weird ways:

<a>
    <b>
        <c />
    </b>
    <b>
        <c />
    </b>
    <b>
        <b>
            <d>
                <b>
                    <e>
                        <f>
                            <c />
                        </f>
                    </e>
                </b>
                <b>
                    <e>
                        <f>
                            <c />
                        </f>
                    </e>
                </b>
            </d>
        </b>
    </b>
    <b>
        <b>
            <c />
        </b>
    </b>
</a>

I want to make it go through each of the tags one by one in the order they appear from top to bottom the repeated tags can be used in any order or structure. I want to go through each tag one by one using beautifulsoup. for example:

soup = BeautifulSoup(xmlcode, "xml")
for asd in soup.findAll(True, recursive=False):
    print asd.prettify()
    print "---------"

All this returns is a single large bs4.element.Tag. I would want it to return 19 lines instead in the order that they appear. Basically all I want to do is go over each single tag using hopefully a single loop or as few loops as possible. Im open to better options than beautifulsoup if possible.

You are looking for .children :

xml_soup = BeautifulSoup(xml, "xml")
for tag in xml_soup.children:
    print tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM