3
2

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にてプロ野球の打率トップ5自動抽出

Posted at

この記事について

プロ野球ファンなら誰しも一度は見たことがあるであろうスポナビにて今回はセリーグ、パリーグに分けたトップ5を抽出しエクセルに出力するツールを作成いたしました。
打率の5傑を確認したいときに最適なツールとなっております。(後で本塁打と打点、OPSも作成予定)
ご興味があればご自由にお使いください。

今回作成したソースコード

※pipでインストールするものは事前にしておいてください。

import requests
from bs4 import BeautifulSoup
import pandas as pd

# URL
url = "https://baseball.yahoo.co.jp/npb/stats"
r = requests.get(url)

# 接続確認
if r.status_code == 200:
    print("接続に成功しました")
else:
    print("接続に失敗しました")

soup = BeautifulSoup(r.text, "lxml")

# 打率データが含まれるセクションを探す
atbat_section = soup.find_all("section", class_="bb-splits__item")

# データを格納するリスト
atbat_data = []

# 各セクションのデータを抽出
for section in atbat_section:
    lines = section.text.strip().split('\n')
    for line in lines:
        if line:
            atbat_data.append(line.strip())

# 出力データの初期化
se_league_data = []
pa_league_data = []

# データの分割と整理
is_se_league = True  # 初期状態はセ・リーグ

for data in atbat_data:
    if 'パ・リーグ' in data:
        is_se_league = False  # パ・リーグに切り替え
    if '順位' in data or '成績一覧を見る' in data:
        continue  # 不要な行をスキップ
    if "本塁打" in data:
        break
    if is_se_league:
        se_league_data.append(data)
    else:
        pa_league_data.append(data)

# データの整形
def format_data(data_list):
    formatted_data = []
    for i in range(1, len(data_list), 4):  # 4つの要素ずつ処理する
        if i + 4 < len(data_list):  # 現在の要素から4つ後にデータがある場合
            player_data = {
                "順位": data_list[i],
                "選手名": data_list[i + 1],
                "チーム名": data_list[i + 2],
                "打率": data_list[i + 3]
            }
            formatted_data.append(player_data)
    return formatted_data

se_league_formatted = format_data(se_league_data)
pa_league_formatted = format_data(pa_league_data)

# DataFrameの作成
se_leagu_df = pd.DataFrame(se_league_formatted).drop(0)
pa_leagu_df = pd.DataFrame(pa_league_formatted).drop(0)

# DataFrameの表示
print("セリーグ 打率データ")
print(se_leagu_df)
print("パリーグ 打率データ")
print(pa_leagu_df)

# エクセル出力
se_leagu_df.to_excel("セリーグ打率データ.xlsx", index=False)
pa_leagu_df.to_excel("パリーグ打率データ.xlsx", index=False)

実行結果

セリーグ.png
パリーグ.png

最後に

いかがでしたでしょうか。
正直それほど難しくなくPythonを知っている人であれば朝飯前だと思いますが、個人的にはPythonで何か作るのは初めてだったのでまあまあの出来でうれしい限りです。
そのうち他の要素も抽出できるコードを書いて野球の試合を見なくてもいいようになりたいです???
ありがとうございました。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?