各ライブラリの役割

requests
HTTP クライアント。URL を指定して HTML を取得する担当。GET / POST・タイムアウト・ヘッダー設定などを担う。
BeautifulSoup4
HTML パーサー。requests が取得した HTML 文字列を Python オブジェクトに変換し、タグ・属性を検索可能にする担当。
lxml
BeautifulSoup のバックエンドパーサー。C 実装で高速。壊れた HTML の修復が得意。本番用途では必ずインストールする。

📌 requests と BeautifulSoup の分業

requests は「HTML の文字列を持ってくる」専門、BeautifulSoup は「持ってきた文字列を解析する」専門。両者は独立しており、BeautifulSoup 単体でローカルの HTML ファイルを読むことも当然できる。

インストール手順

仮想環境を有効化した状態で以下を実行する(仮想環境の作り方は PART 02 を参照)。

Shell — インストール
# requests — HTTP クライアント
pip install requests

# BeautifulSoup4 本体
pip install beautifulsoup4

# lxml — 高速バックエンドパーサー(推奨)
pip install lxml

# まとめて一括インストール
pip install requests beautifulsoup4 lxml

⚠️ パッケージ名に注意

pip install beautifulsoup4(末尾の 4 あり)が正しい。beautifulsoup(4 なし)は古い BS3 で別物。importfrom bs4 import BeautifulSoup と短縮名を使う。

インストール確認

Shell — バージョン確認
pip show requests beautifulsoup4 lxml
出力例
Name: requests
Version: 2.32.3
---
Name: beautifulsoup4
Version: 4.12.3
Requires: soupsieve
---
Name: lxml
Version: 5.2.2

動作確認コード

以下のスクリプトで「HTML を取得してタイトルを抽出できる」ところまで確認する。

Python — hello_bs4.py
import requests
from bs4 import BeautifulSoup

# 1. HTML を取得
url = "https://httpbin.org/html"
response = requests.get(url, timeout=10)
response.raise_for_status()   # 4xx/5xx なら例外を発生させる

# 2. BeautifulSoup でパース
soup = BeautifulSoup(response.text, "lxml")

# 3. タイトルタグを取得
title = soup.find("title")
print("タイトル:", title.get_text() if title else "(なし)")

# 4. h1 タグを全件取得
h1_list = soup.find_all("h1")
for h1 in h1_list:
    print("H1:", h1.get_text(strip=True))
実行結果
タイトル: Herman Melville - Moby-Dick
H1: Herman Melville - Moby-Dick

httpbin.org とは

HTTP リクエストのテスト用サービス。/html エンドポイントはシンプルな HTML を返すため、スクレイピングの動作確認に最適。

パーサーの選び方

パーサー指定文字列速度特徴インストール
lxml HTML "lxml" 速い 壊れた HTML の修復が得意。本番推奨。 pip install lxml
html.parser "html.parser" 普通 Python 標準。追加インストール不要。 不要
html5lib "html5lib" 遅い ブラウザと同一解析。最も寛容。 pip install html5lib

迷ったら "lxml" を使う。lxml が未インストールの環境だけ "html.parser" にフォールバックする構成が堅牢だ。

Python — lxml フォールバック
try:
    import lxml  # noqa
    PARSER = "lxml"
except ImportError:
    PARSER = "html.parser"

soup = BeautifulSoup(html_text, PARSER)

文字エンコーディングの注意

日本語サイトでは Shift_JIS や EUC-JP が使われる場合がある。 requests はレスポンスヘッダーの Content-Type からエンコーディングを推定するが、 誤検出することがある。

Python — エンコーディング対策
response = requests.get(url, timeout=10)

# apparent_encoding は chardet で自動検出(pip install chardet が必要)
response.encoding = response.apparent_encoding

# または meta charset を見て設定する
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content, "lxml")
# response.content(bytes)を渡すと BeautifulSoup が自分で文字コードを推定する

⚠️ 文字化けが起きたら

response.text(str)ではなく response.content(bytes)を BeautifulSoup に渡すと、BS 側が <meta charset> を読んで自動解決することが多い。

次の章では…

PART 04 では JavaScript で描画された動的ページを扱うための Playwright のインストールとブラウザバイナリの取得手順を詳解します。

→ PART 04 — Playwright へ