Here is my stab at it:
>>> from BeautifulSoup import BeautifulSoup
>>> html = """<folder name="folder1">
<folder name="folder2">
<bookmark href="link.html">
</folder>
</folder>
"""
>>> bookmarks = soup.findAll('bookmark')
>>> [p.get('name') for p in bookmarks[0].findAllPrevious(name = 'folder')]
[u'folder2', u'folder1']
The key difference from @eumiro's answer is that I am using findAllPrevious
instead of findParents
. When I tested @eumiro's solution I found that findParents
only returns the first (immediate) parent as the name of the parent and grandparent are the same.
>>> [p.get('name') for p in bookmarks[0].findParents('folder')]
[u'folder2']
>>> [p.get('name') for p in bookmarks[0].findParents()]
[u'folder2', None]
It does return two generations of parents if the parent and grandparent are differently named.
>>> html = """<folder name="folder1">
<folder_parent name="folder2">
<bookmark href="link.html">
</folder_parent>
</folder>
"""
>>> soup = BeautifulSoup(html)
>>> bookmarks = soup.findAll('bookmark')
>>> [p.get('name') for p in bookmarks[0].findParents()]
[u'folder2', u'folder1', None]