Spaces:
Runtime error
Runtime error
Download app.py from Robert1224/ResendApp01: direct link, hf CLI and curl.
- Browser
- Download file 8.84 kB
-
https://huggingface.co/spaces/Robert1224/ResendApp01/resolve/main/app.py
- Command line
-
hf download hf://spaces/Robert1224/ResendApp01/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Robert1224/ResendApp01/resolve/main/app.py
8.84 kB
| import streamlit as st | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import pandas as pd | |
| import resend | |
| from datetime import datetime | |
| # 設定頁面配置 | |
| st.set_page_config( | |
| page_title="公開資訊觀測站爬蟲", | |
| page_icon="📊", | |
| layout="wide" | |
| ) | |
| def scrape_mops_announcement(url): | |
| """ | |
| 抓取公開資訊觀測站的重大訊息資料 | |
| """ | |
| headers = { | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' | |
| } | |
| try: | |
| response = requests.get(url, headers=headers) | |
| response.encoding = 'utf-8' | |
| if response.status_code != 200: | |
| st.error(f"請求失敗,狀態碼: {response.status_code}") | |
| return None | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| data = [] | |
| rows = soup.find_all('tr') | |
| for row in rows: | |
| tds = row.find_all('td') | |
| if len(tds) >= 5: | |
| row_text = row.get_text() | |
| if '公司代號' in row_text or '發言日期' in row_text: | |
| continue | |
| try: | |
| company_code = tds[0].get_text(strip=True) | |
| company_name = tds[1].get_text(strip=True) | |
| announce_date = tds[2].get_text(strip=True) | |
| announce_time = tds[3].get_text(strip=True) | |
| subject = tds[4].get_text(strip=True) | |
| if company_code and company_name: | |
| data.append({ | |
| '公司代號': company_code, | |
| '公司簡稱': company_name, | |
| '發言日期': announce_date, | |
| '發言時間': announce_time, | |
| '主旨': subject | |
| }) | |
| except (IndexError, AttributeError): | |
| continue | |
| if data: | |
| df = pd.DataFrame(data) | |
| return df | |
| else: | |
| st.warning("未找到符合的資料") | |
| return pd.DataFrame() | |
| except Exception as e: | |
| st.error(f"發生錯誤: {e}") | |
| return None | |
| def generate_html_table(df): | |
| """ | |
| 將 DataFrame 轉換為 HTML 表格 | |
| """ | |
| if df is None or df.empty: | |
| return "<p>無資料</p>" | |
| html = """ | |
| <style> | |
| table { | |
| border-collapse: collapse; | |
| width: 100%; | |
| margin: 20px 0; | |
| } | |
| th, td { | |
| border: 1px solid #ddd; | |
| padding: 12px; | |
| text-align: left; | |
| } | |
| th { | |
| background-color: #4CAF50; | |
| color: white; | |
| } | |
| tr:nth-child(even) { | |
| background-color: #f2f2f2; | |
| } | |
| tr:hover { | |
| background-color: #ddd; | |
| } | |
| </style> | |
| """ | |
| html += df.to_html(index=False, escape=False) | |
| return html | |
| def send_email_notification(df, api_key, recipient_email): | |
| """ | |
| 發送包含爬取資料的郵件通知 | |
| """ | |
| resend.api_key = api_key | |
| if df is None or df.empty: | |
| email_body = "<p>本次爬取未找到任何資料。</p>" | |
| data_count = 0 | |
| else: | |
| email_body = f""" | |
| <h2>公開資訊觀測站爬取結果</h2> | |
| <p>本次共爬取到 <strong>{len(df)}</strong> 筆重大訊息資料</p> | |
| {generate_html_table(df)} | |
| <hr> | |
| <p style="color: #666; font-size: 12px;">此郵件由自動化系統發送</p> | |
| """ | |
| data_count = len(df) | |
| params: resend.Emails.SendParams = { | |
| "from": "Acme <onboarding@resend.dev>", | |
| "to": [recipient_email], | |
| "subject": f"公開資訊觀測站爬取通知 - {datetime.now().strftime('%Y-%m-%d %H:%M')}", | |
| "html": email_body, | |
| } | |
| try: | |
| email = resend.Emails.send(params) | |
| return True, email, data_count | |
| except Exception as e: | |
| return False, str(e), 0 | |
| def main(): | |
| # 標題 | |
| st.title("📊 公開資訊觀測站爬蟲系統") | |
| st.markdown("---") | |
| # 側邊欄設定 | |
| with st.sidebar: | |
| st.header("⚙️ 設定") | |
| url = st.text_input( | |
| "目標網址", | |
| value="https://mopsov.twse.com.tw/mops/web/t05sr01_1", | |
| help="請輸入公開資訊觀測站的網址" | |
| ) | |
| st.subheader("郵件設定") | |
| api_key = st.text_input( | |
| "Resend API Key", | |
| value="", | |
| type="password", | |
| help="請輸入您的 Resend API 金鑰" | |
| ) | |
| recipient_email = st.text_input( | |
| "收件人 Email", | |
| value="", | |
| help="請輸入接收通知的 Email 地址" | |
| ) | |
| send_email = st.checkbox("發送郵件通知", value=False) | |
| # 主要內容區 | |
| col1, col2 = st.columns([3, 1]) | |
| with col1: | |
| st.subheader("🔍 資料爬取") | |
| with col2: | |
| scrape_button = st.button("🚀 開始爬取", type="primary", use_container_width=True) | |
| # 執行爬取 | |
| if scrape_button: | |
| with st.spinner("正在爬取資料..."): | |
| df = scrape_mops_announcement(url) | |
| if df is not None and not df.empty: | |
| # 儲存到 session state | |
| st.session_state['df'] = df | |
| st.session_state['scrape_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| st.success(f"✅ 爬取成功!共 {len(df)} 筆資料") | |
| # 發送郵件 | |
| if send_email: | |
| if not api_key or not recipient_email: | |
| st.warning("⚠️ 請先設定 API Key 和收件人 Email") | |
| else: | |
| with st.spinner("正在發送郵件..."): | |
| success, result, count = send_email_notification(df, api_key, recipient_email) | |
| if success: | |
| st.success(f"✅ 郵件發送成功!共 {count} 筆資料") | |
| else: | |
| st.error(f"❌ 郵件發送失敗: {result}") | |
| else: | |
| st.warning("⚠️ 未找到任何資料或爬取失敗") | |
| # 顯示資料 | |
| if 'df' in st.session_state: | |
| df = st.session_state['df'] | |
| st.markdown("---") | |
| st.subheader("📋 爬取結果") | |
| # 統計資訊 | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.metric("總筆數", len(df)) | |
| with col2: | |
| st.metric("公司數量", df['公司代號'].nunique()) | |
| with col3: | |
| st.metric("爬取時間", st.session_state.get('scrape_time', 'N/A')) | |
| # 篩選功能 | |
| st.subheader("🔎 資料篩選") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| company_filter = st.multiselect( | |
| "選擇公司", | |
| options=sorted(df['公司代號'].unique()), | |
| help="可選擇多個公司進行篩選" | |
| ) | |
| with col2: | |
| keyword_filter = st.text_input( | |
| "關鍵字搜尋(主旨)", | |
| help="在主旨中搜尋關鍵字" | |
| ) | |
| # 應用篩選 | |
| filtered_df = df.copy() | |
| if company_filter: | |
| filtered_df = filtered_df[filtered_df['公司代號'].isin(company_filter)] | |
| if keyword_filter: | |
| filtered_df = filtered_df[filtered_df['主旨'].str.contains(keyword_filter, case=False, na=False)] | |
| # 顯示篩選後的資料 | |
| st.dataframe( | |
| filtered_df, | |
| use_container_width=True, | |
| height=400 | |
| ) | |
| # 下載按鈕 | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| csv = filtered_df.to_csv(index=False, encoding='utf-8-sig').encode('utf-8-sig') | |
| st.download_button( | |
| label="📥 下載 CSV", | |
| data=csv, | |
| file_name=f"mops_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv", | |
| mime="text/csv" | |
| ) | |
| with col2: | |
| excel_buffer = pd.ExcelWriter('temp.xlsx', engine='xlsxwriter') | |
| filtered_df.to_excel(excel_buffer, index=False, sheet_name='重大訊息') | |
| excel_buffer.close() | |
| with open('temp.xlsx', 'rb') as f: | |
| st.download_button( | |
| label="📥 下載 Excel", | |
| data=f, | |
| file_name=f"mops_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx", | |
| mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| ) | |
| if __name__ == "__main__": | |
| main() |