180bpm
[python] 로또 당첨 번호 크롤링 스크립트 본문
반응형
ChatGPT한테 추천해달라고 하려고 크롤링 했는데 잘 안되었음
import requests
from bs4 import BeautifulSoup
import csv
def lottery_resust(fr, to):
try:
int(fr)
int(to)
except ValueError as e:
print(f'오류 발생: {e}')
return False
if fr == 0 or fr > to:
print('_from은 0이 아니거나 to보다 작아야 함')
return False
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
}
lottery_list = []
for n in range(fr, to + 1):
url = 'https://www.dhlottery.co.kr/gameResult.do?method=byWin'
payload = {'drwNo': n, 'dwrNoList': n}
req = requests.post(url, headers=headers, data=payload)
lotto_list = []
if req.status_code == 200:
soup = BeautifulSoup(req.text, 'html.parser')
win_res = soup.find('div', attrs=('class','win_result'))
lot_num = [lot.text for lot in win_res.select('div > div.num.win > p > span.ball_645')]
lot_num.insert(0, n)
lot_bonus = win_res.select_one('div > div.num.bonus > p > span').text
lot_num.append(lot_bonus)
lottery_list.append(lot_num)
print(n,'회차 수집 완료')
else:
print('추출 오류입니다!!')
print(lottery_list)
xls_name = f'lotto_{fr}_{to}.csv'
with open(xls_name, 'w', newline='') as f:
csv_obj = csv.writer(f)
header = ['회차', 'N1', 'N2', 'N3', 'N4', 'N5', 'N6', 'Bonus']
csv_obj.writerow(header)
for num in lottery_list:
csv_obj.writerow(num)
if __name__ == '__main__':
_from = 1
to = 1060
lottery_resust(_from, to)
반응형
Comments