import requests from bs4 import BeautifulSoup import pandas as pd from io import BytesIO import gradio as gr # 네이버 증권 상승 종목 스크래핑 함수 def scrape_naver_stock(): 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: cols = row.find_all('td') if len(cols) > 1: # 실제 데이터가 있는 행만 처리 rank = cols[0].text.strip() # 순위 name = cols[1].text.strip() # 종목명 current_price = cols[2].text.strip() # 현재가 change_price = cols[3].text.strip() # 전일비 change_rate = cols[4].text.strip() # 등락률 volume = cols[5].text.strip() # 거래량 # 상승, 하락, 상한가를 구분하여 화살표 이모지 추가 if '+' in change_rate: if '30.00%' in change_rate: change_rate = '🔺 ' + change_rate # 상한가 else: change_rate = '🔴⬆ ' + change_rate # 상승 elif '-' in change_rate: change_rate = '🔵⬇ ' + change_rate # 하락 stock_data.append([rank, name, current_price, change_price, change_rate, volume]) return stock_data # 데이터프레임을 엑셀 파일로 변환하는 함수 def save_to_excel(stock_data): df = pd.DataFrame(stock_data, columns=["순위", "종목명", "현재가", "전일비", "등락률", "거래량"]) output = BytesIO() writer = pd.ExcelWriter(output, engine='openpyxl') df.to_excel(writer, index=False, sheet_name='네이버 증권 상승 종목') writer.save() writer.close() # 엑셀 파일 저장 후 writer를 닫음 output.seek(0) return output # Gradio 인터페이스에서 데이터를 반환하는 함수 def display_stocks(): stock_data = scrape_naver_stock() return pd.DataFrame(stock_data, columns=["순위", "종목명", "현재가", "전일비", "등락률", "거래량"]) # 엑셀 파일로 변환 및 다운로드를 제공하는 함수 def download_excel(): stock_data = scrape_naver_stock() excel_file = save_to_excel(stock_data) return excel_file # Gradio Blocks 내에서 UI 및 이벤트 설정 with gr.Blocks() as app: # 상승 종목을 표시할 DataFrame 컴포넌트 stock_table = gr.DataFrame(label="네이버 증권 상승 TOP 종목", headers=["순위", "종목명", "현재가", "전일비", "등락률", "거래량"]) # 엑셀 다운로드 버튼 download_button = gr.Button("엑셀로 다운로드") # 엑셀 파일 다운로드를 위한 파일 컴포넌트 download_file = gr.File(label="엑셀 파일 다운로드") # 버튼 클릭 시 이벤트 연결 stock_button = gr.Button("종목 데이터 업데이트") stock_button.click(fn=display_stocks, inputs=None, outputs=stock_table) download_button.click(fn=download_excel, inputs=None, outputs=download_file) # 실행 if __name__ == "__main__": app.launch()