ネコでもつくれる人工知能

日記です。1日やったことを書いていきます。内容はそんなにレベルが高くないものになると思います。

【bms】LR2 譜面別上位プレーヤー100名の情報を取得しcsvファイルとして保存

生まれて初めてスクレイピングした時に作ったものです

pythonで実行しましょう

import csv
import urllib.request
from bs4 import BeautifulSoup

try:
    soup = BeautifulSoup(urllib.request.urlopen('http://www.dream-pro.info/~lavalse/LR2IR/search.cgi?mode=ranking&bmsid=545'), "lxml")
except:
    print("エラー urlが開けません")
else:
    print("urlの取得に成功しました")

title = soup.find("h1").string
table = soup.find_all("table")[3]
rows = table.find_all("tr")

try:
    csvfile = open("items/"+ title +".csv", "wt", newline='', encoding='utf-8')
    writer = csv.writer(csvfile)

    for row in rows:
        csvrow = []
        for cell in row.find_all(['td','th']):
            csvrow.append(cell.get_text())
        writer.writerow(csvrow)

except (FileNotFoundError, TypeError):
    print("エラー ファイルが不明です")
else:
    print("ランキングリストの作成に成功しました")
finally:
    csvfile.close()

動きとしては非常に単純です

  1. 取得したい譜面のirにアクセス

  2. テーブルからプレーヤーデータ等を引っこ抜く

  3. そのままcsvに纏める

  4. csvを閉じて終わり