Spaces:
Sleeping
Sleeping
import streamlit as st | |
import requests | |
from bs4 import BeautifulSoup | |
import pandas as pd | |
import time | |
# Set page title and configuration | |
st.set_page_config( | |
page_title="醫院床位狀態查詢", | |
page_icon="🏥", | |
layout="wide" | |
) | |
# Add page header | |
st.title("🏥 成大醫院床位狀態查詢") | |
st.markdown("這個應用程式顯示成大醫院的即時床位狀態資訊") | |
# Function to fetch and process data | |
# Cache data for 5 minutes | |
def fetch_hospital_data(): | |
# URL to fetch data from | |
url = "https://web.hosp.ncku.edu.tw/nckm/Bedstatus/BedStatus.aspx" | |
try: | |
# Send GET request to fetch the raw HTML content | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for bad response codes | |
# Parse HTML content | |
soup = BeautifulSoup(response.text, 'html.parser') | |
# Extract the table with the data | |
table = soup.find('table', {'id': 'GV_EmgInsure'}) | |
if table: | |
# Extract the header and rows of the table | |
headers = [header.text.strip() for header in table.find_all('th')] | |
rows = table.find_all('tr')[1:] # Skip the first row (header) | |
# Extract data from each row | |
data = [] | |
for row in rows: | |
columns = row.find_all('td') | |
data.append([column.text.strip() for column in columns]) | |
# Convert data to pandas DataFrame | |
df = pd.DataFrame(data, columns=headers) | |
return df, None | |
else: | |
return None, "找不到數據表格,網站可能已更改" | |
except requests.exceptions.RequestException as e: | |
return None, f"獲取數據時出錯: {str(e)}" | |
except Exception as e: | |
return None, f"處理數據時出錯: {str(e)}" | |
# Add refresh button and last update time display | |
col1, col2 = st.columns([1, 4]) | |
with col1: | |
if st.button("刷新數據"): | |
st.cache_data.clear() | |
st.success("數據已刷新!") | |
# Display the current time | |
with col2: | |
st.write(f"最後更新時間: {time.strftime('%Y-%m-%d %H:%M:%S')}") | |
# Create a spinner while loading data | |
with st.spinner("正在獲取最新床位數據..."): | |
df, error = fetch_hospital_data() | |
# Display error if any | |
if error: | |
st.error(error) | |
else: | |
# Display dataframe if available | |
if df is not None: | |
# Display summary metrics | |
st.subheader("床位狀態概覽") | |
try: | |
# This assumes there's a column with available beds info | |
# Adjust column names as needed based on actual data | |
if '可用總數' in df.columns: | |
total_available = df['可用總數'].astype(int).sum() | |
st.metric("總可用床位", total_available) | |
# Display the full dataset in a table | |
st.subheader("詳細數據") | |
st.dataframe(df, use_container_width=True) | |
# Add download button | |
csv = df.to_csv(index=False) | |
st.download_button( | |
label="下載CSV檔案", | |
data=csv, | |
file_name="hospital_bed_status.csv", | |
mime="text/csv", | |
) | |
except Exception as e: | |
st.warning(f"處理數據時出錯: {str(e)}") | |
else: | |
st.warning("無法獲取數據,請檢查網絡連接或稍後再試") | |
# Add footer | |
st.markdown("---") | |
st.markdown("數據來源: [成大醫院](https://web.hosp.ncku.edu.tw/nckm/Bedstatus/BedStatus.aspx)") | |
st.markdown("注意: 此應用程式僅用於演示目的,數據每5分鐘自動更新一次") |