IT/Python

[Python - 크롤링] 한국 주식 종가 갖고 오는 프로그램 코드

멋진 선배 2025. 4. 25. 07:08
반응형
반응형

한국 주식 종가 갖고 오는 프로그램 코드

캡쳐본

import requests
from bs4 import BeautifulSoup
import pandas as pd

def get_etf_closing_price(etf_code):
    url = f"https://finance.naver.com/item/main.nhn?code={etf_code}"
    headers = {
        "User-Agent": "Mozilla/5.0"
    }

    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    # ETF 이름 가져오기
    name_tag = soup.select_one("div.wrap_company h2")
    etf_name = name_tag.text.strip() if name_tag else "ETF 이름 없음"

    # 종가 정보는 p 태그 중 class="no_today" 아래에 있음
    price_tag = soup.select_one("p.no_today span.blind")
    if price_tag:
        price_tag = price_tag.text.strip()
    else:
        "종가 정보를 찾을 수 없습니다."

    #return etf_name, price_tag
    return etf_name, price_tag

# ✅ 주요 ETF 코드 10개
etf_codes = [
    "069500", "102110", "278530", "278540", "251340",
    "143850", "252670", "114800", "122630", "233740"
]

# ✅ 이름:종가 딕셔너리 생성
etf_prices = {}
for code in etf_codes:
    name, price = get_etf_closing_price(code)
    etf_prices[name] = price

# ✅ 딕셔너리를 DataFrame으로 → 한 줄로 정렬
df_horizontal = pd.DataFrame([etf_prices])
print(df_horizontal)

# ✅ 엑셀 저장
filename = "ETF_종가_가로표기1.xlsx"
df_horizontal.to_excel(filename, index=False)

print(f"엑셀 저장 완료: {filename}")

국 주식 종가 갖고 오는 프로그램 코드

반응형