라이엇 API 등록(210705 기준)
다양한 롤 데이터들을 지원해주니 API적극 사용 추천
주의 : API 일반 사용에는 데이터 통신에 제한(Limit)가 있으니 주의할 것.
※ 라이엇 API의 규정 및 웹에서 다루는 내용에는 따로 작성하지 않겠습니다.
데이터 수집 목표 : 챌린저, 그랜드마스터 경기 데이터 내용 수집
API내의 변수들을 분석해봤을 때,
summonerId(소환사ID) -> accountId(계정ID) -> gameId(게임의 ID)
//
흐름을 설명하자면
1. 챌린저, 그랜드마스터 등 게임내의 1~500위 까지 소환사닉네임의 ID를 추출한다.
2. 추출한 닉네임ID(닉네임이 아닙니다)를 변수 Input값으로 활용해 계정의 ID를 추출한다.
3. 해당 계정 ID들이 진행한 게임ID값들을 추출한다.
※ 수직적인 구조로 함수가 이루어져있어 하나하나 추출해서 계단식으로 따라가야함
//
1. 모듈 적용
import requests
import json
import time
import pandas as pd
# for문 진행률 확인 라이브러리
from tqdm import tqdm
라이엇에서 받은 API키 입력
api_key = 'RGAPI-qweqw123a-a1c9-12c5-qwe7-1212346546ㅁ'
마스터리그 소환사 ID수집
url = 'https://kr.api.riotgames.com/lol/league/v4/masterleagues/by-queue/RANKED_SOLO_5x5?api_key=' + api_key
summonerId = {}
r = requests.get(url)
r = r.json()['entries'] #소환사의 고유 id
# print(r.json())
num = 0
for i in r:
# print(i)
# print(i['summonerId'], i['summonerName'])
summonerId[i['summonerName']] = i['summonerId']
num += 1
print(num)
# print(summonerId)
계정 ID추출
accountId = {}
for i,j in zip(tqdm(summonerId.values()),summonerId.keys()):
url2 = 'https://kr.api.riotgames.com/lol/summoner/v4/summoners/' + i + '?api_key=' + api_key
r = requests.get(url2)
if r.status_code == 200: # response가 정상이면 바로 맨 밑으로 이동하여 정상적으로 코드 실행
pass
elif r.status_code == 429:
print('api cost full : infinite loop start')
print('loop location : ',i)
start_time = time.time()
while True: # 429error가 끝날 때까지 무한 루프
if r.status_code == 429:
print('try 10 second wait time')
time.sleep(10)
r = requests.get(url2)
print(r.status_code)
elif r.status_code == 200: #다시 response 200이면 loop escape
print('total wait time : ', time.time() - start_time)
print('recovery api cost')
break
r = r.json()['accountId']
print(r)
accountId[j] = r
게임 ID추출
gameId = []
# url3 = 'https://kr.api.riotgames.com/lol/match/v4/matchlists/by-account/hqMv8JiT0hjKc96iqUz9ucXFPgsENmbI_5OHPmlyVOCZxwE?queue=420&api_key=RGAPI-e456f533-671c-4947-b960-98443960695b'
for i in tqdm(accountId.values()):
url3 = 'https://kr.api.riotgames.com/lol/match/v4/matchlists/by-account/' + i + '?queue=420&api_key=' + api_key
r = requests.get(url3)
if r.status_code == 200: # response가 정상이면 바로 맨 밑으로 이동하여 정상적으로 코드 실행
pass
elif r.status_code == 429:
print('api cost full : infinite loop start')
print('loop location : ',i)
start_time = time.time()
while True: # 429error가 끝날 때까지 무한 루프
if r.status_code == 429:
print('try 10 second wait time')
time.sleep(10)
r = requests.get(url2)
print(r.status_code)
elif r.status_code == 200: #다시 response 200이면 loop escape
print('total wait time : ', time.time() - start_time)
print('recovery api cost')
break
try:
r = r.json()['matches']
for j in r:
j = j['gameId']
gameId.append(j)
except:
print(i)
print(r.text)
print('matches 오류 확인불가')
중복게임 제거
print(len(gameId))
set_gameId = set(gameId)
set_gameId = list(set(gameId))
Pandas를 활용해 데이터 수집
match_grandmaster = pd.DataFrame(columns = ['teamId','win','firstBlood','firstTower','firstInhibitor','firstBaron','firstDragon','firstRiftHerald','towerKills','inhibitorKills','baronKills','dragonKills','riftHeraldKills','gameId'])
wait_num = []
for i in range(len(set_gameId)):
if i % 30 == 0:
wait_num.append(i)
※ 수집에 Limit가 걸려있어 해당 시간에 타이머를 두고 수집을 진행하기위한 작업을 진행
num = 0
for i in tqdm(set_gameId[9991:]):
num += 1
if num % 30 == 0:
print("wait_time")
time.sleep(60)
url4 = 'https://kr.api.riotgames.com/lol/match/v4/matches/' + str(i) +'?api_key=' + api_key
r = requests.get(url4)
if r.status_code == 200: # response가 정상이면 바로 맨 밑으로 이동하여 정상적으로 코드 실행
pass
elif r.status_code == 429:
print('api cost full : infinite loop start')
print('loop location : ',i)
start_time = time.time()
while True: # 429error가 끝날 때까지 무한 루프
if r.status_code == 429:
print('try 10 second wait time')
time.sleep(10)
r = requests.get(url2)
print(r.status_code)
elif r.status_code == 200: #다시 response 200이면 loop escape
print('total wait time : ', time.time() - start_time)
print('recovery api cost')
break
try:
r = r.json()['teams']
r = r[0]
input_data = {
'teamId':r['teamId'],
'win':r['win'],
'firstBlood':r['firstBlood'],
'firstTower':r['firstTower'],
'firstInhibitor':r['firstInhibitor'],
'firstBaron':r['firstBaron'],
'firstDragon':r['firstDragon'],
'firstRiftHerald':r['firstRiftHerald'],
'towerKills':r['towerKills'],
'inhibitorKills':r['inhibitorKills'],
'baronKills':r['baronKills'],
'dragonKills':r['dragonKills'],
'riftHeraldKills':r['riftHeraldKills'],
'gameId': i
}
match_grandmaster = match_grandmaster.append(input_data, ignore_index = True)
except:
print("403 에러..?")
match_grandmaster.to_csv("new_match_grandmaster2.csv", header=False, index = False)
데이터 저장
print(match_grandmaster[:45719])
# print
match_grandmaster[:45720].to_csv("new_match_grandmaster2.csv", header=False, index = False)
'머신러닝 > 머신러닝 프로젝트' 카테고리의 다른 글
#2-2 롤(LOL) 게임 데이터 요소를 이용한 승리예측 - [머신러닝 프로젝트] (4) | 2021.07.05 |
---|---|
#2 롤(LOL) 챔피언 조합 데이터 크롤링(OP.GG 크롤링) - [머신러닝 프로젝트] (0) | 2021.06.07 |
#1 롤(LOL) 챔피언 조합 데이터 크롤링(OP.GG 페이지 분석) - [머신러닝 프로젝트] (0) | 2021.06.07 |