kkuzil.own@gmail.com

Posted
Filed under Development/Python
로또의 모든 회차 결과를 가져와서 파일로 저장한다.

매번 모든 회차를 가져오면 번거로우므로,
최초 한번 이후에는 최신 회차만 가져오도록 기능한다.

데이터는 사이트에서 가져온 json 포맷 그대로 라인 단위로 저장한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import requests
 
URL_GetLottoNumber = "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo="
 
def LottoDataAllToFile(sPath, bClear = False):        
    if (bClear == False) and os.path.exists(sPath):
        fData = open(sPath, mode="r+t", encoding="utf-8")
        LdList = fData.readlines()
        i = len(LdList)
        print("로또 데이터 이어서 저장 (최근 %d회차)" % i)
        i += 1
    else:
        fData = open(sPath, mode="wt", encoding="utf-8")
        i = 1
        print("로또 데이터 초기화")
    try:
        nAddCnt = 0
        while True:
            try:
                resp = requests.get(URL_GetLottoNumber + str(i))
                jsResult = resp.json()
                if jsResult["returnValue"!= "success":
                    break
                fData.write(str(jsResult) + "\n")
                nAddCnt += 1
            except Exception as E:
                print(str(E))
                break
            print("%d회차 추가완료.." % (i))
            i += 1
        if nAddCnt > 0:
            print("로또 데이터 가져오기 끝 (새로 가져온 회차 수 : %d, 마지막 회차 : %d)" % (nAddCnt, i - 1))
        else:
            print("새로운 회차 데이터 없음")
    finally:
        fData.close
 
# 함수 실행
LottoDataAllToFile("LottoData.dat")
cs
2018/12/17 23:28 2018/12/17 23:28