【将棋】【Python】seleniumを使って、棋譜のURLをスクレイピングする
はじめに
将棋のデータ分析をしてみたくて、Pythonのスクレイピングを学んでみた。目標は、棋士の戦法別勝率、同一局面検索、戦型ごとの対局数をグラフ化して流行している戦型を見つける、などができればと考えている。
勉強に使った教材
Python × スクレイピング https://www.youtube.com/playlist?list=PL4Y-mUWLK2t1LehwHVwAqxXTXw5xd-Yq8
スクレイピングに必要なselenium,BeautifulSoup,requestsなどの扱い方がわかりやすく説明されている。
将棋DB2サイトにある棋譜を自動で取得
こちらのサイトはほぼ全てのプロ棋戦の棋譜が載っているので、これを題材に行なった。ソースコードは以下。
from time import sleep from selenium import webdriver from selenium.webdriver.chrome.options import Options import pandas as pd chrome_path = '/Users/○○○○○○○/chromedriver' options = Options() options.add_argument('--incognito') #URLにアクセス driver = webdriver.Chrome(executable_path=chrome_path, options=options) url = 'https://shogidb2.com/latest/page/{}' d_list = [] #1ページ目から5ページまでを取得する for i in range(1,6): target_url = url.format(i) driver.get(target_url) sleep(2) elements = driver.find_elements_by_class_name('list-group-item') #list-group-item内の取得したい要素を取ってくる for element in elements: tournament = element.find_element_by_tag_name('p').text first_and_second = element.find_elements_by_class_name('h5') first_move = first_and_second[0].text second_move = first_and_second[1].text tactics = element.find_element_by_class_name('text-right').text kihu_url = element.get_attribute('href') #リストに格納する d = { '先手': first_move, '後手': second_move, '棋戦': tournament, '戦法': tactics, 'url': kihu_url } d_list.append(d) sleep(2) #csvファイルにするためにpandasを使用 df = pd.DataFrame(d_list) df.to_csv('○○○○○○○.csv') #ブラウザを閉じる driver.quit()
これを実行して生成されたcsvファイルがこちら。
課題
まとめ
seleniumを使って、棋譜のURLを自動で取得することができた。まだ上記であげた課題が残るので、次回以降改善していきたいと思う。 記事に関することで質問や何か聞きたいことがコメント or TwitterのDMまで。お気軽にどうぞ。 https://twitter.com/atsu__shogi