4.prettify ()

1.prettify ():把要解析的字符串以标准的缩进格式化输出
<实例如下:

html ="""
<html>
	<head>
	<title>The Dormouse's story</title>
	</heads>
	<body>
	<p class="title" name="dromouse">cb>The Dormouse's story</b></p>
	<p class="story">Once upon a time there were three little sisters; and their names were
	<a href="http://example.com/elsie" class="sister" id="link1"><1-- Elsie --></a>,
	<a href="http://example.com/lacie" class="sister" id="link2">lacie</a> and
	<a href-"http://example.com/tillie" class="sister" id-"link3">Tillie </a>;
	and they lived at the bottom of a well.</p>
	<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())

输出结果如下

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title" name="dromouse">
   cb&gt;The Dormouse's story
  </p>
  <p class="story">
   Once upon a time there were three little sisters; and their names were
   <a class="sister" href="http://example.com/elsie" id="link1">
    &lt;1-- Elsie --&gt;
   </a>
   ,
   <a class="sister" href="http://example.com/lacie" id="link2">
    lacie
   </a>
   and
   <a class="sister" href-="" id-="">
    Tillie
   </a>
   ;
	and they lived at the bottom of a well.
  </p>
  <p class="story">
   ...
  </p>
 </body>
</html>
posted @ 2026-11-09 20:32  abner_pan  阅读(8)  评论(0)    收藏  举报