import csv
import time

from bs4 import BeautifulSoup
from selenium.webdriver import Chrome, ChromeOptions
import chromedriver_binary

def input_int(output):
    try:
        return int(input(output))
    except:
        print("数列を入力してください")
        return input_int(output)


if __name__ == "__main__":
    race_id = input_int("レースIDの上10桁を入力してください:")
    race_sum = input_int("何レースまで開催されたか入力してください:")

    # ドライバのセットアップ
    options = ChromeOptions()
    # options.add_argument('--headless')
    driver = Chrome(options=options)

    target_url = "https://race.netkeiba.com/race/result.html?race_id={id}"

    race_number = []
    race_name = []
    horse_number = []
    horse_name = []
    horse_rank = []
    horse_jockey = []

    for i in range(1, race_sum + 1) :
        # HTML取得
        html = driver.get(target_url.format(id=str(race_id) + str(i).zfill(2)))
        time.sleep(1)
        html = driver.page_source.encode('utf-8')
        soup = BeautifulSoup(html, 'html.parser')

        race_number_html = soup.select_one('span[class="RaceNum"]')
        race_number_tmp = race_number_html.text
        race_name_html = soup.select_one('div[class="RaceName"]')
        race_name_tmp = race_name_html.text.replace('\n','')

        soup = soup.find(class_="ResultTableWrap")

        # 着順取得
        horse_rank_html = soup.select('div[class="Rank"]')
        for item in horse_rank_html :
            race_number.append(race_number_tmp[:-1])
            race_name.append(race_name_tmp)
            horse_rank.append(item.text)

        # 馬番取得
        horse_number_html = soup.select('td[class="Num Txt_C"]')
        for item in horse_number_html :
            horse_number.append(item.text.replace('\n',''))

        # 馬名取得
        horse_name_html = soup.select('span[class*="Horse_Name"]')
        for item in horse_name_html :
            item_tmp = item.text.replace('\n','')
            horse_name.append(item_tmp.replace(' ',''))

        # 騎手取得
        horse_jockey_html = soup.select('td[class="Jockey"]')
        for item in horse_jockey_html :
            item = item.text.replace('\n','')
            horse_jockey.append(item.replace(' ',''))

    driver.close()

    header = ["race_number", "race_name", "horse_num", "horse_name", "arrival", "jockey_name"]
    result = [race_number, race_name, horse_number, horse_name, horse_rank, horse_jockey]
    result = list(map(list, zip(*result)))

    with open(str(race_id)+'_result.csv', 'w', encoding='utf-8') as file:
        writer = csv.writer(file, lineterminator='\n')
        writer.writerow(header)
        writer.writerows(result)