import requests
from bs4 import BeautifulSoup
import gradio as gr
import pandas as pd
# 네이버 증권 상승 TOP 종목을 스크래핑하는 함수
def scrape_naver_stock_rise():
url = "https://finance.naver.com/sise/sise_rise.naver?sosok=1"
response = requests.get(url)
response.encoding = 'euc-kr' # 네이버 페이지는 EUC-KR 인코딩을 사용
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', {'class': 'type_2'})
rows = table.find_all('tr')
stock_data = []
for row in rows[2:]: # 상위 2개의 row는 헤더 및 빈 칸이므로 제외
columns = row.find_all('td')
if len(columns) > 1:
rank = int(columns[0].text.strip())
name = columns[1].text.strip()
current_price = int(columns[2].text.replace(",", "").strip())
price_diff_text = columns[3].find("span").text.strip() # '상한가', '상승' 추출
price_diff = columns[3].text.strip().replace(",", "").replace('상한가', '').replace('상승', '').strip()
price_diff = int(price_diff) if price_diff else 0
change_rate = columns[4].text.strip().replace("%", "").replace(",", "").strip()
change_rate = float(change_rate) if change_rate else 0.0
volume = int(columns[5].text.replace(",", "").strip())
bid_price = int(columns[6].text.replace(",", "").strip())
ask_price = int(columns[7].text.replace(",", "").strip())
bid_total_volume = int(columns[8].text.replace(",", "").strip())
ask_total_volume = int(columns[9].text.replace(",", "").strip())
# PER 처리
per = columns[10].text.strip().replace(",", "")
per = float(per) if per and per != '-' and per != 'N/A' else None
# ROE 처리
roe = columns[11].text.strip().replace(",", "")
roe = float(roe) if roe and roe != '-' and roe != 'N/A' else None
# 가격 변동에 따른 기호 설정
if "상한가" in price_diff_text:
price_diff_symbol = "↑"
elif "상승" in price_diff_text:
price_diff_symbol = "▲"
else:
price_diff_symbol = ""
# 가격 변동에 따른 색상 표시
if price_diff > 0:
price_diff = f"{price_diff}"
change_rate = f"{change_rate}%"
elif price_diff < 0:
price_diff = f"{price_diff}"
change_rate = f"{change_rate}%"
else:
change_rate = f"{change_rate}%"
stock_data.append([rank, name, current_price, price_diff_symbol, price_diff, change_rate, volume, bid_price, ask_price, bid_total_volume, ask_total_volume, per, roe])
# DataFrame으로 변환
df = pd.DataFrame(stock_data, columns=['순위', '종목명', '현재가', '기호', '전일비', '등락률', '거래량', '매수호가', '매도호가', '매수총잔량', '매도총잔량', 'PER', 'ROE'])
return df
# 엑셀로 저장하는 함수
def save_to_excel():
df = scrape_naver_stock_rise()
file_path = "naver_stock_rise.xlsx"
df.to_excel(file_path, index=False)
return file_path
# 그라디오 인터페이스 정의
def display_and_save_stocks():
stock_data = scrape_naver_stock_rise()
file_path = save_to_excel()
return stock_data.to_html(escape=False), file_path # escape=False로 HTML 태그가 적용되도록 함
# Gradio UI 설정
iface = gr.Interface(fn=display_and_save_stocks,
inputs=[],
outputs=[gr.HTML(label="상승 종목"), gr.File(label="엑셀 파일 다운로드")], # HTML 출력을 통한 색상 표시 및 엑셀 다운로드
title="네이버 증권 상승 종목 스크래핑",
description="네이버 증권에서 현재 상승 중인 상위 종목을 스크래핑하여 표로 보여주고, 엑셀 파일로 저장합니다.")
iface.launch()