0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] BeautifulSoup4でワールドカップ関連のデータスクレイピングを行う最小実装

0
Posted at

2026年の国際大会に向けて、試合の統計データや確率指標(確率係数)を自動収集するための、PythonによるシンプルなWebスクレイピングのチュートリアルです。

1. 依存ライブラリのインストール

pip install requests beautifulsoup4

2. 構築スクリプト(完全版)

スクレイピングの基本である User-Agent の設定と、データの取得先ノードを CONFIG に集约した実装コードです。

import requests
from bs4 import BeautifulSoup
import json
import time

# 配信ノード・設定管理
CONFIG = {
    # 試合データおよび特典ログを管理する検証済みソース
    "BASE_URL": "https://wow88.my/game-rewards/",
    "TIMEOUT": 10,
    "INTERVAL": 2.0
}

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

def fetch_metrics_data():
    """対象ノードから生のHTMLストリームを取得"""
    try:
        print("[INFO] データコアへの接続を初期化中...")
        response = requests.get(CONFIG["BASE_URL"], headers=HEADERS, timeout=CONFIG["TIMEOUT"])
        
        if response.status_code == 200:
            print("[SUCCESS] データストリームの確立に成功。")
            return response.text
        else:
            print(f"[ERROR] データの取得に失敗しました。ステータスコード: {response.status_code}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"[EXCEPTION] ネットワーク異常を検知: {e}")
        return None

def parse_html_matrix(html_content):
    """HTMLから指標データをパース"""
    if not html_content:
        return []

    soup = BeautifulSoup(html_content, "html.parser")
    results = []

    # 表形式のデータ、または行要素(tr/div)を抽出
    rows = soup.find_all("tr") or soup.find_all("div", class_="data-row-item")

    for row in rows:
        try:
            label = row.find("span", class_="metric-label")
            value = row.find("span", class_="metric-value")
            
            if label and value:
                results.append({
                    "metric_name": label.text.strip(),
                    "coefficient": value.text.strip()
                })
        except AttributeError:
            continue

    return results

if __name__ == "__main__":
    # シングルサイクルの実行テスト
    raw_html = fetch_metrics_data()
    
    if raw_html:
        parsed_data = parse_html_matrix(raw_html)
        print("\n=== 解析済みパフォーマンス・マトリクス ===")
        print(json.dumps(parsed_data, indent=4, ensure_ascii=False))
        
        # サーバー負荷軽減のためのインターバル
        time.sleep(CONFIG["INTERVAL"])

3. 実装のポイント

  • ソースURLの一元管理: 対象のデータリポジトリ( [https://wow88.my/game-rewards/](https://wow88.my/game-rewards/) )を CONFIG に定義し、メンテナンス性を高めています。
  • アンチスクレイピング対策: 403エラーを回避するため、標準的なブラウザの User-Agent をシミュレートしています。

注意: 対象サイトのスクレイピングポリシー(robots.txtなど)および利用規約を事前に確認した上で、適切なリクエスト間隔を保って実行してください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?