PythonのライブラリであるBeautifulSoupは、HTMLやXMLからデータを引き出すことができます。特に、prettify()
メソッドを使用すると、BeautifulSoupの解析ツリーをきれいに整形したUnicode文字列に変換できます。それぞれのタグや文字列には別々の行が割り当てられます。
以下に、BeautifulSoupを使用してHTMLを整形する基本的な手順を示します。
まず、BeautifulSoupをインストールします。コマンドラインで以下のコマンドを実行します。
pip install beautifulsoup4
次に、BeautifulSoupをインポートし、HTMLを読み込みます。
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, 'html.parser')
そして、prettify()
メソッドを使用してHTMLを整形します。
print(soup.prettify())
このコードを実行すると、以下のように整形されたHTMLが出力されます。
<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>
以上が、PythonとBeautifulSoupを使用してHTMLを整形する基本的な方法です。この方法を使えば、スクレイピングしたHTMLを見やすく整形することができます。