BeautifulSoup是一個用於從HTML和XML文件中提取數據的python庫,它提供一些簡單的函數來處理導航、搜索、修改分析樹等功能。BeautifulSoup能自動將文檔轉換成Unicode編碼,輸出文檔轉換為UTF-8編碼。
本例直接創建模擬HTML代碼,進行美化:
# 導入BeautifulSoup庫 from bs4 import BeautifulSoup # 創建模擬HTML代碼的字符串 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>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">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> """ # 創建一個BeautifulSoup對象,獲取頁面正文 soup = BeautifulSoup(html_doc, features="lxml") # 打印解析的HTML代碼 print('經BeautifulSoup美化的代碼:',soup) print('===================================') print('通過prettify()方法進行代碼的格式化處理:',soup.prettify())
結果:
經BeautifulSoup美化的代碼: <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></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">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> </body></html> =================================== 通過prettify()方法進行代碼的格式化處理: <html> <head> <title> The Dormouse's story </title> </head> <body> <p class="title"> <b> The Dormouse's story </b> </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"> Elsie </a> , <a class="sister" href="http://example.com/lacie" id="link2"> Lacie </a> and <a class="sister" href="http://example.com/tillie" id="link3"> Tillie </a> ; and they lived at the bottom of a well. </p> <p class="story"> ... </p> </body> </html>