pocketyのブログ

日記です。

pandasでnetkeibaをスクレイピング


import pandas as pd
import requests
import lxml.html
import time # サーバーに負担をかけないために
from tqdm import tqdm #どのくらい読み込んだかを表示

# レース場、第何回、何日目、何レース目
# 01:札幌、02:函館、03:福島、05:東京、06:中山、07:中京、08:京都、09:阪神、10:小倉

# race_idを入れたら読み込んでくれるfor文
def scrape_race_results(race_id_list):
race_results = {} # 辞書型
for race_id in tqdm(race_id_list): #tqdm race_id_listにどのくらい読み込んだかを表示
try: # IndexErrorが出ても無視して続けるようにする
race_results[race_id] = pd.read_html(url)[0]
time.sleep(1) # 1秒待機 サーバーに負担をかけない
except IndexError:
continue
return race_results


# strは整数型を文字列に変換、zfillは桁数を入れる EX 01 02
race_id_list = []
for place in range(1,11,1): #1から10まで一個づつ
for kai in range(1,6,1): #何回まで開催されているか
for day in range(1,9,1):
for r in range(1,13,1):
race_id = '2019' + str(place).zfill(2) + str(kai).zfill(2) + str(day).zfill(2) + str(r).zfill(2)
race_id_list.append(race_id)


test = scrape_race_results(race_id_list) # 結果をtestに変換


# どのレースか知りたいので Index に race_id を入れる
for key in test.keys():
test[key].index = [key] * len(test[key]) # keyにrace_idが入っている、dataframeの長さの分だけrace_idにIndexを書き換える

print(test)

# pandasのDataframe型に変換してpickleファイルで保存する
test = pd.concat([test[key] for key in test], sort=False) # これがないとpickleでもopenpyxlでもattributeエラーがでる。

import pickle
test.to_pickle('results.pickle')

import openpyxl
test.to_excel("excelresults.xlsx")

# 後で読み込むときは
# pd.read_pickle(results.pickle)