본문 바로가기

하루코딩/python 하루코딩

[python & 데이터] KBO 랭크 가져오기

728x90
반응형
from bs4 import BeautifulSoup
import numpy as np
import requests

res = requests.get(html_url)
soup = BeautifulSoup(res.text, 'html.parser')

kbo_data = [i.text for i in soup.select( "#cphContents_cphContents_cphContents_udpRecord >table td")]
lists = [0,1,3,4,5,6]
kbo_data = [value for idx, value in enumerate(kbo_data) if idx%12 in lists][:60]
kbo_ranks = np.array(kbo_data).reshape((10,6))
head = np.array(["순위","팀","승","무","패","승률"])
result = np.vstack([head,kbo_ranks])

with open("rank.txt","w",encoding="utf-8") as file:
    file.write("=========================KBO 순위=========================\n")
    for row in range(len(result)):
        for col in range(result.shape[1]):
            file.write(f"{result[row][col]:<5}\t")
        file.write("\n")

with open("rank.txt",'r',encoding="utf-8") as file:
    data = file.read()
    print(data)

 

반응형