获取HTML代码的结构

Mil*_*ano 4 html python beautifulsoup

我正在使用BeautifulSoup4,我很好奇是否有一个函数返回HTML代码的结构(有序标签).

这是一个例子:

<html>
<body>
<h1>Simple example</h1>
<p>This is a simple example of html page</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

print page.structure():

>>
<html>
<body>
<h1></h1>
<p></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我试图找到解决方案,但没有成功.

谢谢

roi*_*ppi 6

据我所知,没有一点递归应该有效:

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

演示:

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>'
Run Code Online (Sandbox Code Playgroud)

  • 太感谢了。这正是我一直在寻找的东西。 (2认同)