获取HTML代码结构

6 投票
2 回答
2977 浏览
提问于 2025-04-18 12:33

我正在使用BeautifulSoup4,想知道有没有一个函数可以返回HTML代码的结构(有序的标签)。

这里有个例子:

<html>
<body>
<h1>Simple example</h1>
<p>This is a simple example of html page</p>
</body>
</html>

打印 page.structure():

>>
<html>
<body>
<h1></h1>
<p></p>
</body>
</html>

我试着找解决办法,但没有成功。

谢谢

2 个回答

2

简单的Python正则表达式可以实现你想要的功能:

import re

html = '''<html>
<body>
<h1>Simple example</h1>
<p>This is a simple example of html page</p>
</body>
</html>'''

structure = ''.join(re.findall(r'(</?.+?>|/n+?)', html))

这个方法可以保留换行符。

11

据我所知,似乎没有现成的解决方案,不过稍微用一下递归应该可以解决这个问题:

def taggify(soup):
     for tag in soup:
         if isinstance(tag, bs4.Tag):
             yield '<{}>{}</{}>'.format(tag.name,''.join(taggify(tag)),tag.name)

示例:

html = '''<html>
 <body>
 <h1>Simple example</h1>
 <p>This is a simple example of html page</p>
 </body>
 </html>'''

soup = BeautifulSoup(html)

''.join(taggify(soup))
Out[34]: '<html><body><h1></h1><p></p></body></html>'

撰写回答