Converting HTML list to nested Python list

怎甘沉沦 提交于 2019-11-30 16:08:35

问题


If I have a nested html (unordered) list that looks like this:

<ul>
    <li><a href="Page1_Level1.html">Page1_Level1</a> 
    <ul>
        <li><a href="Page1_Level2.html">Page1_Level2</a> 
            <ul>
                <li><a href="Page1_Level3.html">Page1_Level3</a></li>
            </ul>
            <ul>
                <li><a href="Page2_Level3.html">Page2_Level3</a></li>
            </ul>
            <ul>
                <li><a href="Page3_Level3.html">Page3_Level3</a></li>
            </ul>
        </li>
    </ul>
    </li>
    <li><a href="Page2_Level1.html">Page2_Level1</a> 
    <ul>
        <li><a href="Page2_Level2.html">Page2_Level2</a></li>
    </ul>
    </li>
</ul>

How do I form a nested list out of it in Python? For example:

["Page1_Level1.html", ["Page1_Level2.html", ["Page1_Leve3.html", "Page2_Level3.html", "Page3_Level3.html"]], "Page2_Level1.html", ["Page2_Level2.html"]]

I presume libraries like Beautiful Soup and HTML Parser have facilities to do this, but I haven't been able it figure it out. Thanks for any help / pointers!


回答1:


You can take a recursive approach:

from pprint import pprint
from bs4 import BeautifulSoup

text = """your html goes here"""

def find_li(element):
    return [{li.a['href']: find_li(li)}
            for ul in element('ul', recursive=False)
            for li in ul('li', recursive=False)]


soup = BeautifulSoup(text, 'html.parser')
data = find_li(soup)
pprint(data)

Prints:

[{u'Page1_Level1.html': [{u'Page1_Level2.html': [{u'Page1_Level3.html': []},
                                                 {u'Page2_Level3.html': []},
                                                 {u'Page3_Level3.html': []}]}]},
 {u'Page2_Level1.html': [{u'Page2_Level2.html': []}]}]

FYI, here is why I had to use html.parser here:

  • Don't put html, head and body tags automatically, beautifulsoup



回答2:


It is an overview of a possible solution

# variable 'markup' contains the html string
from bs4 import BeautifulSoup
soup = BeautifulSoup(markup)
for a in soup.descendants:
   # construct a nested list when going thru the descendants
   print id(a), id(a.parent) if a.parent else None, a


来源:https://stackoverflow.com/questions/24216263/converting-html-list-to-nested-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!