Title: How do I get a list of all parent tags in BeautifulSoup?
Tags: python;html-parsing;beautifulsoup;xml-parsing
Question: Let's say I have a structure like this:
<folder name="folder1"&gt;
<folder name="folder2"&gt;
<bookmark href="link.html"&gt;
</folder&gt;
</folder&gt;
If I point to bookmark, what would be the command to just extract all of the folder lines?
For example,
bookmarks = soup.findAll('bookmark')
then beautifulsoupcommand(bookmarks[0]) would return:
[<folder name="folder1"&gt;,<folder name="folder2"&gt;]
I'd also want to know when the ending tags hit too. Any ideas?
Thanks in advance!

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

Here is another answer: bookmarks[0].findParents('folder') will return you a list of all parent nodes. You can then iterate over them and use their name attribute.
Comment for this answer: BS only returns the first (immediate) parent as the name of the parent and grandparent are the same. It does return two generations of parents if the parent and grandparent are differently named.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2010:00:09/20/10', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<python><html-parsing><beautifulsoup><xml-parsing>', 'Title': 'How do I get a list of all parent tags in BeautifulSoup?', 'ViewCount': 8249, 'id': 3752327, 'user_AboutMe': '', 'user_AccountId': 151727.0, 'user_DisplayName': 'FinDev', 'user_Reputation': 4127.0, 'user_Views': 121.0, 'user_id': 365781.0}}