メインコンテンツへスキップ
見出し画像

【Python 100日チャレンジ】Day 53 - BeautifulSoup基礎

    🕵️ Web ページから欲しい情報だけを抽出!

    • soup.find_all("h1") → すべての見出しを一括取得

    • soup.select(".price") → 価格情報だけをピンポイント抽出

    ニュースの見出し収集、商品価格の比較、不動産情報の取得など、
    Web ページから必要な情報を自動で集める方法を学びます!!

    (目安時間:30〜40分 ⭐⭐⭐)

    🎯 今日の学習目標

    1. BeautifulSoupライブラリをインストールして使う

    2. HTMLパースと要素選択を理解する

    3. CSSセレクタで要素を検索する

    4. 実践Webスクレイピング例を作成する

    📚 事前知識


    🎯 学習目標 1: BeautifulSoupライブラリをインストールして使う

    1.1 BeautifulSoupとは?

    BeautifulSoupはHTMLとXML文書をパース(解析)してデータを抽出するPythonライブラリです。

    主な機能:

    • HTML/XML文書のパースとツリー構造生成

    • タグ、クラス、IDで要素検索

    • CSSセレクタによる強力な要素選択

    • ツリー走査(親、子、兄弟要素)

    • 属性値抽出とテキスト内容取得

    1.2 インストール

    # BeautifulSoupインストール
    pip install beautifulsoup4
    
    # パーサライブラリ(オプション、より高速)
    pip install lxml

    インストール確認:

    python -c "from bs4 import BeautifulSoup; print('BeautifulSoup インストール完了!')"

    パーサ比較:

    • html.parser: 速度は普通、柔軟性は普通、標準内蔵(インストール不要)

    • lxml: 速度は速い、柔軟性は高い、別途インストール必要

    • html5lib: 速度は遅い、柔軟性はとても高い、別途インストール必要

    おすすめ: lxml(高速で安定)、インストールできない場合はhtml.parserを使用

    1.3 基本的な使い方

    from bs4 import BeautifulSoup
    import requests
    
    # 1. Webページを取得
    url = 'https://example.com'
    response = requests.get(url)
    
    # 2. BeautifulSoupオブジェクト作成
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # または lxml パーサを使用
    soup = BeautifulSoup(response.text, 'lxml')
    
    # 3. データ抽出
    title = soup.find('title')
    print(title.string)  # ページタイトル

    1.4 ローカルHTMLファイルのパース

    from bs4 import BeautifulSoup
    
    # ファイルから読み込み
    with open('index.html', 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # または文字列を直接パース
    html = """
    <html>
    <head><title>テストページ</title></head>
    <body>
        <h1>メインタイトル</h1>
        <p>本文内容</p>
    </body>
    </html>
    """
    
    soup = BeautifulSoup(html, 'html.parser')

    🎯 学習目標 2: HTMLパースと要素選択

    2.1 基本的な要素アクセス

    from bs4 import BeautifulSoup
    
    html = """
    <html>
    <head><title>テストページ</title></head>
    <body>
        <h1 class="main-title">メインタイトル</h1>
        <p id="intro">紹介文です。</p>
        <ul>
            <li>項目 1</li>
            <li>項目 2</li>
            <li>項目 3</li>
        </ul>
    </body>
    </html>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # タイトル取得
    print(soup.title)         # <title>テストページ</title>
    print(soup.title.string)  # テストページ
    print(soup.title.name)    # title
    
    # h1タグ(最初のみ)
    print(soup.h1)            # <h1 class="main-title">メインタイトル</h1>
    print(soup.h1.string)     # メインタイトル
    
    # bodyタグ
    print(soup.body)

    出力:

    <title>テストページ</title>
    テストページ
    title
    <h1 class="main-title">メインタイトル</h1>
    メインタイトル
    <body>
        <h1 class="main-title">メインタイトル</h1>
        ...
    </body>

    2.2 find() - 最初の要素を探す

    # タグ名で検索
    h1 = soup.find('h1')
    print(h1.string)  # メインタイトル
    
    # クラスで検索
    title = soup.find(class_='main-title')
    print(title.string)  # メインタイトル
    
    # IDで検索
    intro = soup.find(id='intro')
    print(intro.string)  # 紹介文です。
    
    # 複数条件を同時に
    p_with_id = soup.find('p', id='intro')
    print(p_with_id.string)

    2.3 find_all() - 全ての要素を探す

    # 全てのliタグ
    lis = soup.find_all('li')
    print(f"liタグの数: {len(lis)}")
    
    for i, li in enumerate(lis, 1):
        print(f"{i}. {li.string}")

    出力:

    liタグの数: 3
    1. 項目 1
    2. 項目 2
    3. 項目 3

    2.4 高度な検索オプション

    html = """
    <div>
        <p class="text">1番目</p>
        <p class="text highlight">2番目</p>
        <p class="text">3番目</p>
        <span class="text">4番目</span>
    </div>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # クラスが完全一致する要素
    exact = soup.find_all('p', class_='text')
    print(f"完全一致: {len(exact)}個")  # 2個(highlightは含まない)
    
    # クラスを含む要素
    contains = soup.find_all(class_='text')
    print(f"含む要素: {len(contains)}個")  # 4個(全て)
    
    # 複数クラス(リストで)
    multi = soup.find_all(class_=['text', 'highlight'])
    for elem in multi:
        print(elem)
    
    # 複数タグを同時検索
    mixed = soup.find_all(['p', 'span'])
    print(f"pまたはspan: {len(mixed)}個")

    2.5 属性で検索

    html = """
    <a href="https://example.com" class="external">外部リンク</a>
    <a href="/about" class="internal">内部リンク</a>
    <img src="/photo.jpg" alt="写真" width="300">
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # 属性の存在で検索
    links = soup.find_all('a', href=True)
    print(f"リンク数: {len(links)}")
    
    # 属性値で検索
    external = soup.find('a', href='https://example.com')
    print(external.string)  # 外部リンク
    
    # 属性値を取得
    img = soup.find('img')
    print(img['src'])        # /photo.jpg
    print(img.get('alt'))    # 写真
    print(img.get('width'))  # 300

    🎯 学習目標 3: CSSセレクタで要素を検索

    3.1 select() メソッド

    CSSセレクタはWeb開発で使用される強力な選択文法です。

    html = """
    <html>
    <body>
        <h1 id="main-title">メインタイトル</h1>
        <div class="container">
            <p class="text">1番目の段落</p>
            <p class="text highlight">2番目の段落</p>
            <ul>
                <li>項目 1</li>
                <li>項目 2</li>
            </ul>
        </div>
        <footer>
            <p>フッターテキスト</p>
        </footer>
    </body>
    </html>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # 1. タグセレクタ
    h1s = soup.select('h1')
    print(f"h1の数: {len(h1s)}")
    
    # 2. クラスセレクタ (.)
    texts = soup.select('.text')
    print(f".textの数: {len(texts)}")
    
    # 3. IDセレクタ (#)
    title = soup.select('#main-title')
    print(title[0].string)
    
    # 4. 子孫セレクタ (スペース)
    container_ps = soup.select('.container p')
    print(f"container内のp: {len(container_ps)}")
    
    # 5. 子セレクタ (>)
    direct_children = soup.select('div > p')
    print(f"divの直接の子p: {len(direct_children)}")
    
    # 6. 複数クラスを同時に
    highlight = soup.select('.text.highlight')
    print(highlight[0].string)

    出力:

    h1の数: 1
    .textの数: 2
    メインタイトル
    container内のp: 2
    divの直接の子p: 2
    2番目の段落

    3.2 select_one() - 最初だけ

    # 最初のマッチのみ返す(リストではない!)
    first_p = soup.select_one('p')
    print(first_p.string)  # 1番目の段落
    
    first_text = soup.select_one('.text')
    print(first_text.string)
    
    # 要素がなければNoneを返す
    none = soup.select_one('.non-existent')
    print(none)  # None

    3.3 高度なCSSセレクタ

    html = """
    <div class="products">
        <article class="product" data-category="electronics">
            <h3>ノートPC</h3>
            <span class="price">1000000</span>
        </article>
        <article class="product" data-category="books">
            <h3>Python本</h3>
            <span class="price">30000</span>
        </article>
        <article class="product" data-category="electronics">
            <h3>マウス</h3>
            <span class="price">25000</span>
        </article>
    </div>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # 属性セレクタ []
    electronics = soup.select('[data-category="electronics"]')
    print(f"電子製品: {len(electronics)}個")
    
    # 全てのpriceを抽出
    prices = soup.select('.product .price')
    for price in prices:
        print(f"価格: {price.string}円")
    
    # nth-of-type (n番目の要素)
    second_product = soup.select('.product:nth-of-type(2)')
    print(second_product[0].h3.string)  # Python本

    3.4 実践例: ニュース記事パース

    html = """
    <div class="article">
        <h2 class="title">ニュースタイトル 1</h2>
        <p class="summary">要約内容 1</p>
        <span class="author">記者 A</span>
        <time class="date">2025-04-22</time>
    </div>
    <div class="article">
        <h2 class="title">ニュースタイトル 2</h2>
        <p class="summary">要約内容 2</p>
        <span class="author">記者 B</span>
        <time class="date">2025-04-21</time>
    </div>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # 全ての記事を抽出
    articles = soup.select('.article')
    print(f"合計 {len(articles)}件の記事\n")
    
    for i, article in enumerate(articles, 1):
        title = article.select_one('.title').string
        summary = article.select_one('.summary').string
        author = article.select_one('.author').string
        date = article.select_one('.date').string
    
        print(f"[記事 {i}]")
        print(f"タイトル: {title}")
        print(f"要約: {summary}")
        print(f"著者: {author}")
        print(f"日付: {date}")
        print("-" * 50)

    🎯 学習目標 4: 実践Webスクレイピング例

    4.1 ニュースヘッドラインスクレイピング

    import requests
    from bs4 import BeautifulSoup
    
    def scrape_news_headlines(url):
        """ニュースサイトからヘッドラインを抽出"""
        try:
            # User-Agent設定(重要!)
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
    
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
    
            soup = BeautifulSoup(response.text, 'html.parser')
    
            # 例: タイトルが <h2 class="headline">にあると仮定
            headlines = soup.select('.headline')
    
            articles = []
            for headline in headlines:
                title = headline.get_text(strip=True)
                link = headline.find('a')
    
                if link:
                    articles.append({
                        'title': title,
                        'url': link.get('href', '')
                    })
    
            return articles
    
        except requests.exceptions.RequestException as e:
            print(f"リクエストエラー: {e}")
            return []
        except Exception as e:
            print(f"パースエラー: {e}")
            return []
    
    # 使用例(実際のURLに置き換え)
    # headlines = scrape_news_headlines('https://news.example.com')
    # for i, article in enumerate(headlines, 1):
    #     print(f"{i}. {article['title']}")
    #     print(f"   リンク: {article['url']}\n")

    4.2 HTMLテーブルデータ抽出

    def scrape_table(url):
        """HTMLテーブルを辞書リストに変換"""
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
    
        # 最初のテーブルを探す
        table = soup.find('table')
    
        if not table:
            print("テーブルが見つかりません。")
            return []
    
        data = []
    
        # ヘッダー抽出
        headers = []
        header_row = table.find('thead')
        if header_row:
            ths = header_row.find_all('th')
            headers = [th.get_text(strip=True) for th in ths]
    
        # データ行抽出
        tbody = table.find('tbody')
        rows = tbody.find_all('tr') if tbody else table.find_all('tr')
    
        for row in rows:
            cells = row.find_all(['td', 'th'])
            row_data = [cell.get_text(strip=True) for cell in cells]
    
            if row_data:
                if headers:
                    # ヘッダーがあれば辞書に
                    data.append(dict(zip(headers, row_data)))
                else:
                    # なければリストに
                    data.append(row_data)
    
        return data

    実践例:

    # 簡単なテーブルHTML
    html = """
    <table>
        <thead>
            <tr>
                <th>名前</th>
                <th>年齢</th>
                <th>職業</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>山田太郎</td>
                <td>30</td>
                <td>開発者</td>
            </tr>
            <tr>
                <td>佐藤花子</td>
                <td>25</td>
                <td>デザイナー</td>
            </tr>
        </tbody>
    </table>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # ヘッダー
    headers = [th.string for th in soup.select('thead th')]
    print("ヘッダー:", headers)
    
    # データ
    for row in soup.select('tbody tr'):
        cells = [td.string for td in row.find_all('td')]
        print(dict(zip(headers, cells)))

    出力:

    ヘッダー: ['名前', '年齢', '職業']
    {'名前': '山田太郎', '年齢': '30', '職業': '開発者'}
    {'名前': '佐藤花子', '年齢': '25', '職業': 'デザイナー'}

    4.3 画像ダウンロード

    import os
    from urllib.parse import urljoin
    
    def download_images(url, save_dir='images'):
        """ページの全ての画像をダウンロード"""
        # 保存ディレクトリ作成
        os.makedirs(save_dir, exist_ok=True)
    
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
    
        # 全てのimgタグ
        images = soup.find_all('img')
        print(f"合計 {len(images)}枚の画像を発見")
    
        for i, img in enumerate(images, 1):
            img_url = img.get('src')
    
            if not img_url:
                continue
    
            # 相対URLを絶対URLに変換
            img_url = urljoin(url, img_url)
    
            try:
                # 画像ダウンロード
                img_response = requests.get(img_url, timeout=10)
                img_response.raise_for_status()
    
                # ファイル名(拡張子保持)
                ext = img_url.split('.')[-1].split('?')[0]  # クエリパラメータ除去
                filename = f'image_{i:03d}.{ext}'
                filepath = os.path.join(save_dir, filename)
    
                # バイナリで保存
                with open(filepath, 'wb') as f:
                    f.write(img_response.content)
    
                print(f"✅ {filename} ダウンロード完了")
    
            except Exception as e:
                print(f"❌ {img_url} ダウンロード失敗: {e}")
    
    # 使用
    # download_images('https://example.com')

    4.4 ツリー走査実践例

    html = """
    <div id="parent">
        <h2>タイトル</h2>
        <p>1番目の段落</p>
        <p>2番目の段落</p>
        <ul>
            <li>項目 1</li>
            <li id="current">項目 2</li>
            <li>項目 3</li>
        </ul>
    </div>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # 親要素を探す
    current = soup.find(id='current')
    print("親:", current.parent.name)  # ul
    
    # 兄弟要素
    print("前の兄弟:", current.find_previous_sibling().string)  # 項目 1
    print("次の兄弟:", current.find_next_sibling().string)      # 項目 3
    
    # 子要素
    div = soup.find(id='parent')
    print("\n子要素:")
    for child in div.children:
        if child.name:  # タグのみ(空白テキスト除外)
            print(f"- {child.name}: {child.get_text(strip=True)}")

    💡 実践のコツと注意点

    ✅ こうしましょう

    1. 常にUser-Agentを設定

    headers = {'User-Agent': 'Mozilla/5.0 ...'}
    requests.get(url, headers=headers)

    2. 要素の存在確認後に使用

    title = soup.find('h1')
    if title:
        print(title.string)
    else:
        print("タイトルなし")

    3. タイムアウト設定

    requests.get(url, timeout=10)

    4. 例外処理必須

    try:
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
    except Exception as e:
        print(f"エラー: {e}")

    5. robots.txt確認

    ❌ やってはいけないこと

    1. 過度なリクエスト禁止

    # 悪い例: 連続リクエスト
    for i in range(1000):
        requests.get(f'https://example.com/page/{i}')
    
    # 良い例: 遅延を追加
    import time
    for i in range(100):
        requests.get(f'https://example.com/page/{i}')
        time.sleep(1)  # 1秒待機

    2. Noneチェックなしで属性アクセス

    # 危険: titleがNoneの可能性
    print(soup.find('title').string)
    
    # 安全
    title = soup.find('title')
    print(title.string if title else "タイトルなし")

    3. エンコーディング問題を無視

    # 文字化け防止
    response.encoding = 'utf-8'
    soup = BeautifulSoup(response.text, 'html.parser')

    🧪 練習問題

    問題 1: ブログポストスクレイパー

    次のHTMLから全てのブログポストのタイトル、日付、タグを抽出してください。

    html = """
    <div class="posts">
        <article class="post">
            <h2 class="title">Python基礎講座</h2>
            <time>2025-04-20</time>
            <div class="tags">
                <span class="tag">python</span>
                <span class="tag">tutorial</span>
            </div>
        </article>
        <article class="post">
            <h2 class="title">Webスクレイピング入門</h2>
            <time>2025-04-22</time>
            <div class="tags">
                <span class="tag">scraping</span>
                <span class="tag">beautifulsoup</span>
            </div>
        </article>
    </div>
    """
    
    # TODO: 各ポストの情報を辞書で抽出してください

    💡 ヒント

    1. soup.select('.post')で全てのポストを探す

    2. 各ポストでselect_one()でタイトル、日付を抽出

    3. select('.tag')で全てのタグを抽出


    ✅ 解答

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html, 'html.parser')
    
    posts = []
    for post in soup.select('.post'):
        title = post.select_one('.title').string
        date = post.select_one('time').string
        tags = [tag.string for tag in post.select('.tag')]
    
        posts.append({
            'title': title,
            'date': date,
            'tags': tags
        })
    
    # 出力
    for i, post in enumerate(posts, 1):
        print(f"[ポスト {i}]")
        print(f"タイトル: {post['title']}")
        print(f"日付: {post['date']}")
        print(f"タグ: {', '.join(post['tags'])}\n")

    出力:

    [ポスト 1]
    タイトル: Python基礎講座
    日付: 2025-04-20
    タグ: python, tutorial
    
    [ポスト 2]
    タイトル: Webスクレイピング入門
    日付: 2025-04-22
    タグ: scraping, beautifulsoup

    問題 2: 価格比較スクレイパー

    商品リストから最安値と最高値を見つけてください。

    html = """
    <div class="products">
        <div class="product">
            <h3>ノートPC A</h3>
            <span class="price">1200000</span>
        </div>
        <div class="product">
            <h3>ノートPC B</h3>
            <span class="price">950000</span>
        </div>
        <div class="product">
            <h3>ノートPC C</h3>
            <span class="price">1500000</span>
        </div>
    </div>
    """
    
    # TODO: 最安値/最高値の商品を見つけてください

    ✅ 解答

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html, 'html.parser')
    
    products = []
    for product in soup.select('.product'):
        name = product.h3.string
        price = int(product.select_one('.price').string)
        products.append({'name': name, 'price': price})
    
    # 最安値/最高値
    min_product = min(products, key=lambda x: x['price'])
    max_product = max(products, key=lambda x: x['price'])
    
    print(f"最安値: {min_product['name']} - {min_product['price']:,}円")
    print(f"最高値: {max_product['name']} - {max_product['price']:,}円")

    出力:

    最安値: ノートPC B - 950,000円
    最高値: ノートPC C - 1,500,000円

    📝 今日学んだ内容のまとめ

    主要メソッド一覧:

    • パース: BeautifulSoup(html, 'html.parser') → HTMLをパース可能なオブジェクトに変換

    • 単一検索: find('tag') → 最初のマッチ要素を返す

    • 全体検索: find_all('tag') → 全てのマッチ要素をリストで返す

    • CSS選択: select('.class') → CSSセレクタで全体検索

    • CSS単一: select_one('#id') → CSSセレクタで最初だけ

    • テキスト取得: element.string または get_text() → 要素のテキスト内容

    • 属性取得: element['attr'] または get('attr') → 属性値を取得

    核心コードパターン:

    # 1. 基本スクレイピングパターン
    from bs4 import BeautifulSoup
    import requests
    
    response = requests.get(url, headers=headers, timeout=10)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 2. 要素検索
    elements = soup.find_all('tag', class_='classname')
    # または
    elements = soup.select('.classname')
    
    # 3. 安全なデータ抽出
    for elem in elements:
        text = elem.get_text(strip=True)
        attr = elem.get('href', '')  # デフォルト値提供

    🔗 関連資料


    📚 前回の学習

    Day 52:HTTPメソッドとステータス ⭐⭐⭐
    前回は、GET、POST、PUT、PATCH、DELETEとHTTPステータスコードを学びました!

    📚 次回の学習

    Day 54: Webスクレイピング高度 ⭐⭐⭐⭐(準備中)
    次回は、動的ページ、ページネーション、セッション管理など高度なスクレイピング技術を学びます!

    📚 シリーズをまとめて読む

    Python 100日チャレンジの全記事は、
    マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
    よろしければ、フォローしていただけると嬉しいです!


    🚀 遅いと思った時が一番早い時期です!🚀
    Day 53/100 | Phase 6: WebスクレイピングとAPI | #100DaysOfPython

    よんよんわれ
     
     
    ソフトウェアエンジニアです。 ものづくりが好きで、プライベートでも複数のサイドプロジェクトに取り組んでいます。 最近は、AIと自動化を活用したサービス開発に力を入れています。 Note、Xなどでお友達になっていただけたら嬉しいです☺️

    あなたへのおすすめ