Python: BeautifulSoup 使い方(タイトル・HTML 取得など)

TwitterFacebookHatena
  • 公開:2021-11-25
  • 更新:2023-10-26
  • 文章量:2302
  • Python

TL;DR

BeautifulSoup モジュール は、HTML や XML ファイルからタイトルやヘディングを取得することができるモジュールである。正規表現を組み合わせれば、様々な情報を整形して取得することが可能である。

BeautifulSoup モジュールのポイント

  • HTML から要素を取得出力する
  • html タグは除去可能
  • 深い階層の要素まで絞り込みできる
pip install beautifulsoup4

ドキュメント:Beautiful Soup 4.9.0 documentation

基本の形

find() メソッドの引数に条件を指定することで、html のタグを取得することができる。Tag は BeautifulSoup の Tag オブジェクトのことである。

# Tag オブジェクトを返す
soup.find("タグ")

# 指定した属性に一致するTagオブジェクトを返す
soup.find(属性=属性値)

# 指定したタグと属性に一致するTagオブジェクトを返す
soup.find("タグ", 属性=属性値)

# Tag のシーケンス
soup.find_all("タグ")

# タグの名前
Tag.name

# タグの中のテキスト
Tag.text

# 属性の値
Tag.get("属性名")

使用例

print(soup.p)
# <p class="text_en">Lorem ipsum dolor sit amet consequat.</p>

print(soup.a)
# <a class="underline" href="#">これはダミーリンクです。</a>

find メソッド

次は、変数 html_doc に、ダミー HTML を格納し、find メソッドによって p タグの中身を取得する例である。

html_doc = """
<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <title>HTML Document Template</title>
  <meta name="description" content="これはhtmlのテンプレートです。">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <h1>Hello, World!</h1>
  <p class="text_en">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
  <p class="text_ja">これはダミーのパラグラフです。</p>
  <a class="underline" href="#">これはダミーリンクです。</a>
</body>

</html>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

# pタグのみを取得
print(soup.find('p'))
# <p class="text_en">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>

# pタグ内のテキストのみを取得
print(soup.find('p').text)
# Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

find_all メソッド

find_all メソッドを使用すれば、特定のタグが持つすべての要素を取得することが可能である。

# 全てのpタグを取得
print(soup.find_all('p'))
# [<p class="text_en">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>, <p class="text_ja">これはダミーのパラグラフです。</p>]

# pタグ内の全てのテキストを取得
for tag in soup.find_all('p'):
    print(tag.text)
# Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
# これはダミーのパラグラフです。

get メソッド

get メソッドを使うと、タグの属性を取得することができる。

# href属性を取得
print(soup.find('a').get('href'))
# #

BeautifulSoup は非常に強力で、HTML や XML の解析に広く使用されています。以上がその基本的な使い方になりますが、これらのメソッドや機能を組み合わせることで、様々な情報抽出や加工が可能です。

Python: BeautifulSoup 使い方(タイトル・HTML 取得など)