BeautifulSoupはPythonのライブラリで、HTMLやXMLファイルからデータを取得するために使用されます。あなたの好きなパーサーを使って、パースツリーの探索、検索、修正を行うことができます。
以下に、BeautifulSoupを使って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, 'html.parser')
これで、BeautifulSoupオブジェクトを使ってHTMLドキュメントを探索、検索、修正することができます。
例えば、以下のようにHTMLドキュメントのタイトルを取得することができます。
print(soup.title)
# <title>The Dormouse's story</title>
また、以下のようにすべての<a>
タグを取得することもできます。
print(soup.find_all('a'))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
このように、BeautifulSoupはHTMLやXMLファイルからデータを取得するための強力なツールです。詳細な情報や使用例については、公式ドキュメンテーションを参照してください。