Update app.py
Browse files9 unmodified lines1011121314151631 unmodified lines484950515253547 unmodified lines62636465666768695 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532542552562572589 unmodified linesfrom datetime import datetime# --- 1. 初始化與檔案路徑 ---st.set_page_config(page_title="政府採購網工作站 - 進階版", page_icon="🕷️", layout="wide")HISTORY_FILE = "crawled_history.txt"def load_history():31 unmodified linesreturn {"User-Agent": random.choice(ua_list)}def parse_html_core(html_content):"""解析標案詳情頁面 (內容抓取最精準)"""soup = BeautifulSoup(html_content, 'html.parser')title_node = soup.find(class_="title_1")data = {"公告類型": title_node.get_text(strip=True) if title_node else "N/A"}7 unmodified linesfields = {"公告日": "公告日", "機關名稱": "機關名稱", "標案案號": "標案案號","標案名稱": "標案名稱", "預算/決標金額": ["總決標金額", "預算金額", "預算金額(元)"],"截止日期": ["截止投標", "開標時間"]}for k, v in fields.items():if isinstance(v, list):5 unmodified lineselse: data[k] = find_value(v)return data# --- 3. UI 設計 ---st.title("🕷️ 政府採購網 - 全自動進階工作站")with st.sidebar:st.header("⚙️ 控制面板")mode = st.radio("模式選擇", ["🔍 關鍵字搜尋", "🔗 網址直爬", "📂 異步解析"])st.divider()st.subheader("💾 案號去重資料庫")history_str = st.text_area("歷史案號清單", value="\n".join(st.session_state['crawled_ids']), height=150)if st.button("💾 儲存歷史"):new_ids = set([i.strip() for i in history_str.split("\n") if i.strip()])st.session_state['crawled_ids'] = new_idssave_history(new_ids)st.toast("✅ 已更新")st.divider()st.subheader("🕷️ 爬蟲設定")search_limit = st.selectbox("每頁筆數", [10, 20, 50, 100], index=2)min_d = st.slider("最小延遲", 1, 10, 3)max_d = st.slider("最大延遲", 11, 40, 15)# --- 5. 主程式邏輯 ---if mode == "🔍 關鍵字搜尋":# 搜尋 UIcurr_yr = datetime.now().year - 1911yrs = [str(curr_yr - i) for i in range(5)]c1, c2, c3 = st.columns([3, 1, 2])with c1: kw = st.text_input("搜尋關鍵字", value="農田水利署")with c2: yr = st.selectbox("年度 (民國)", yrs)with c3:status_sel = st.multiselect("標案狀態", ["招標", "決標", "公開閱覽", "更正"], default=["招標"])# --- 智慧過濾面板 ---with st.expander("🛠️ 進階隱藏過濾器 (搜尋後執行)", expanded=False):f1, f2 = st.columns(2)with f1:ex_kw = st.text_input("🚫 排除關鍵字", placeholder="多個請空格分隔")inc_kw = st.text_input("🎯 必須包含", placeholder="例如:維修 工程")with f2:min_money = st.number_input("💰 預算下限 (萬元)", min_value=0, value=0)date_filter = st.date_input("📅 只看此日期之後截止的標案", value=None)show_crawled = st.checkbox("顯示資料庫已有的標案", value=True)if st.button("🔎 搜尋並自動對齊欄位"):with st.spinner("通訊中... 正在處理採購網 HTML 結構偏移..."):p = {"querySentence": kw, "tenderStatusType": status_sel, "sortCol": "TENDER_NOTICE_DATE", "timeRange": yr, "pageSize": search_limit}try:# 採用全文檢索網址,相容性最高r = requests.get("https://web.pcc.gov.tw/prkms/tender/common/bulletion/readBulletion", params=p, headers=get_dynamic_headers(), timeout=20)soup = BeautifulSoup(r.text, 'html.parser')table = soup.find('table', id='bulletion') or soup.find('table', id='tpam')if table:# --- A. 智慧表頭對位 ---headers = [th.get_text(strip=True) for th in table.find_all('th')]def find_idx(keywords):return next((i for i, h in enumerate(headers) if any(k in h for k in keywords)), -1)idx_org = find_idx(["機關"])idx_id_name = find_idx(["案號", "名稱"])idx_date = find_idx(["日期", "公告日"])idx_money = find_idx(["預算", "金額"])links = []ex_list = [x.strip().lower() for x in ex_kw.split()]inc_list = [x.strip().lower() for x in inc_kw.split()]# --- B. 逐行解析 ---for row in table.select('tbody tr'):cols = row.find_all('td')if len(cols) < 5 or "無符合" in row.get_text(): continue# 處理案號名稱合併欄位 (對應招標查詢格式)cell_id_name = cols[idx_id_name]# 處理換行,提取案號與標題lines = [l.strip() for l in cell_id_name.get_text("|", strip=True).split("|") if l.strip()]raw_id = lines[0] if lines else "N/A"raw_name = lines[1] if len(lines) > 1 else raw_id# 案號去雜質if "]" in raw_id:raw_id = raw_id.split("]")[0].replace("[", "").strip()link_node = cell_id_name.find('a')tender_url = "https://web.pcc.gov.tw" + link_node.get('href') if link_node else ""org_name = cols[idx_org].get_text(strip=True) if idx_org != -1 else "N/A"date_str = cols[idx_date].get_text(strip=True) if idx_date != -1 else "N/A"# 金額智慧清理 (解決預算金額為 0 問題)money_raw = cols[idx_money].get_text(strip=True) if idx_money != -1 else "0"money_num = "".join(filter(str.isdigit, money_raw))try:m_val = float(money_num) / 10000 if money_num else 0except: m_val = 0# --- C. 過濾邏輯 ---is_crawled = raw_id in st.session_state['crawled_ids']if not show_crawled and is_crawled: continueif ex_list and any(x in raw_name.lower() or x in org_name.lower() for x in ex_list): continueif inc_list and not any(x in raw_name.lower() for x in inc_list): continueif min_money > 0 and m_val < min_money: continueif date_filter:try:y, m, d = map(int, date_str.split("/"))if datetime(y + 1911, m, d).date() < date_filter: continueexcept: passlinks.append({"勾選": not is_crawled,"狀態": "🚫 已記錄" if is_crawled else "⭐ 新標案","標案案號": raw_id,"標案名稱": raw_name,"預算(萬)": round(m_val, 1),"日期/截止": date_str,"機關": org_name,"網址": tender_url})st.session_state['search_list'] = linksst.success(f"符合條件共 {len(links)} 筆")else:st.warning("查無標案,請檢查關鍵字或日期範圍")except Exception as e:st.error(f"連線異常: {e}")# 顯示編輯列表if st.session_state['search_list']:df = pd.DataFrame(st.session_state['search_list'])edited_df = st.data_editor(df, use_container_width=True, hide_index=True)if st.button("🚀 開始安全爬取 (詳情抓取)"):targets = edited_df[edited_df["勾選"] == True]if not targets.empty:st.session_state['temp_results'] = []pbar = st.progress(0)for i, (_, row) in enumerate(targets.iterrows()):time.sleep(random.uniform(min_d, max_d))try:res = requests.get(row['網址'], headers=get_dynamic_headers(), timeout=15)# 進入詳情頁面,這時抓到的金額最精準p_data = parse_html_core(res.text)p_data['網址'] = row['網址']st.session_state['temp_results'].append(p_data)st.session_state['crawled_ids'].add(row['標案案號'])save_history(st.session_state['crawled_ids'])except: passpbar.progress((i + 1) / len(targets))if st.session_state['temp_results']:2 unmodified linesoutput = io.BytesIO()with pd.ExcelWriter(output, engine='openpyxl') as writer:res_df.to_excel(writer, index=False)st.download_button("📥 下載完整 Excel", output.getvalue(), f"Result_{datetime.now().strftime('%m%d')}.xlsx")elif mode == "🔗 網址直爬":urls_in = st.text_area("請輸入網址 (一行一個)")if st.button("開始執行"):urls = [u.strip() for u in urls_in.split('\n') if u.strip()]st.session_state['temp_results'] = []for u in urls:time.sleep(2)try:r = requests.get(u, headers=get_dynamic_headers())d = parse_html_core(r.text); d['網址'] = ust.session_state['temp_results'].append(d)except: passst.dataframe(pd.DataFrame(st.session_state['temp_results']))elif mode == "📂 異步解析":files = st.file_uploader("上傳 HTML", accept_multiple_files=True)if files and st.button("一秒解析"):with concurrent.futures.ThreadPoolExecutor() as executor:res = list(executor.map(lambda f: parse_html_core(f.getvalue().decode("utf-8", errors="ignore")), files))st.dataframe(pd.DataFrame(res))st.divider()st.caption(f"目前資料庫案號數: {len(st.session_state['crawled_ids'])}")9 unmodified lines1011121314151631 unmodified lines4849505152537 unmodified lines61626364656667685 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901912 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242259 unmodified linesfrom datetime import datetime# --- 1. 初始化與檔案路徑 ---st.set_page_config(page_title="115年政府採購網工作站", page_icon="🕷️", layout="wide")HISTORY_FILE = "crawled_history.txt"def load_history():31 unmodified linesreturn {"User-Agent": random.choice(ua_list)}def parse_html_core(html_content):soup = BeautifulSoup(html_content, 'html.parser')title_node = soup.find(class_="title_1")data = {"公告類型": title_node.get_text(strip=True) if title_node else "N/A"}7 unmodified linesfields = {"公告日": "公告日", "機關名稱": "機關名稱", "標案案號": "標案案號","標案名稱": "標案名稱", "預算/決標金額": ["總決標金額", "預算金額"],"截止/開標日期": ["截止投標", "開標時間"]}for k, v in fields.items():if isinstance(v, list):5 unmodified lineselse: data[k] = find_value(v)return datadef fast_file_processor(uploaded_file):try:content = uploaded_file.getvalue().decode("utf-8", errors="ignore")res = parse_html_core(content); res['來源檔名'] = uploaded_file.namereturn resexcept Exception as e:return {"來源檔名": uploaded_file.name, "錯誤": str(e)}# --- 3. UI 設計 ---st.title("🕷️ 政府採購網 - 雲端多功能工作站")with st.sidebar:st.header("⚙️ 控制面板")mode = st.radio("模式選擇", ["🔍 關鍵字搜尋", "🔗 網址直爬", "📂 異步解析"])st.divider()st.subheader("💾 案號去重資料庫")history_str = st.text_area("歷史案號清單 (支援手動貼入)",value="\n".join(st.session_state['crawled_ids']),height=150)col_save, col_clear = st.columns(2)with col_save:if st.button("💾 儲存變更"):new_ids = set([i.strip() for i in history_str.split("\n") if i.strip()])st.session_state['crawled_ids'] = new_idssave_history(new_ids)st.toast("✅ 歷史記錄已同步")with col_clear:if st.button("🗑️ 清空歷史"):st.session_state['crawled_ids'] = set()save_history(set())st.rerun()st.divider()st.subheader("🕷️ 爬蟲參數設定")search_limit = st.selectbox("搜尋結果每頁筆數", [10, 20, 50, 100], index=2)min_d = st.slider("爬取最小延遲", 1, 10, 3)max_d = st.slider("爬取最大延遲", 11, 40, 15)# --- 5. 主程式邏輯 ---if mode == "🔍 關鍵字搜尋":curr_yr = datetime.now().year - 1911yrs = [str(curr_yr - i) for i in range(5)]col1, col2 = st.columns([3, 1])with col1: kw = st.text_input("搜尋關鍵字", value="農田水利署")with col2: yr = st.selectbox("年度範圍 (民國)", yrs)status_options = ["招標", "決標", "公開閱覽及公開徵求", "更正"]status_sel = st.multiselect("標案狀態 (可複選)", status_options, default=["招標"])if st.button("🔎 搜尋並過濾重複項"):if not status_sel:st.warning("請至少選擇一種標案狀態")else:with st.spinner("通訊中..."):p = {"querySentence": kw, "tenderStatusType": status_sel, "sortCol": "TENDER_NOTICE_DATE", "timeRange": yr, "pageSize": search_limit}try:r = requests.get("https://web.pcc.gov.tw/prkms/tender/common/bulletion/readBulletion",params=p, headers=get_dynamic_headers(), timeout=20)soup = BeautifulSoup(r.text, 'html.parser')table = soup.find('table', id='bulletion')if table:links = []for row in table.select('tbody tr'):cols = row.find_all('td')if len(cols) > 3:title_node = cols[3].find('a')if title_node:full_title = title_node.get_text(strip=True)# 簡單穩定的拆分邏輯:案號與名稱分開case_id = full_title.split("]")[0].replace("[", "") if "]" in full_title else full_titlecase_name = full_title.split("]")[1] if "]" in full_title else full_titleis_crawled = case_id in st.session_state['crawled_ids']links.append({"勾選": not is_crawled,"狀態": "🚫 已爬過" if is_crawled else "⭐ 新標案","案號": case_id,"標案名稱": case_name.strip(),"機關": cols[2].get_text(strip=True),"網址": "https://web.pcc.gov.tw" + title_node.get('href')})st.session_state['search_list'] = linksst.success(f"成功找到 {len(links)} 筆標案!")else:st.warning("找不到相關標案。")except Exception as e:st.error(f"連線失敗: {e}")if st.session_state['search_list']:st.info(f"💡 系統已自動排除側邊欄記錄中的標案。")df = pd.DataFrame(st.session_state['search_list'])edited_df = st.data_editor(df, use_container_width=True, hide_index=True)if st.button("🚀 開始安全爬取 (中途可斷開)"):targets = edited_df[edited_df["勾選"] == True]if targets.empty:st.warning("請勾選標案。")else:st.session_state['temp_results'] = []pbar = st.progress(0)for i, (_, row) in enumerate(targets.iterrows()):time.sleep(random.uniform(min_d, max_d))try:res = requests.get(row['網址'], headers=get_dynamic_headers(), timeout=15)if "驗證碼" in res.text:st.error(f"🛑 觸發驗證碼!進度保留至 {row['案號']}")breakp_data = parse_html_core(res.text)p_data['網址'] = row['網址']st.session_state['temp_results'].append(p_data)st.session_state['crawled_ids'].add(row['案號'])save_history(st.session_state['crawled_ids'])except:st.session_state['temp_results'].append({"案號": row['案號'], "狀態": "失敗"})pbar.progress((i + 1) / len(targets))if st.session_state['temp_results']:2 unmodified linesoutput = io.BytesIO()with pd.ExcelWriter(output, engine='openpyxl') as writer:res_df.to_excel(writer, index=False)st.download_button("📥 下載 Excel 結果檔", output.getvalue(), f"Tenders_{datetime.now().strftime('%m%d_%H%M')}.xlsx")elif mode == "🔗 網址直爬":urls_in = st.text_area("請輸入網址 (一行一個)")if st.button("🚀 開始爬取"):urls = [u.strip() for u in urls_in.split('\n') if u.strip()]if urls:st.session_state['temp_results'] = []pbar = st.progress(0)for i, u in enumerate(urls):time.sleep(random.uniform(min_d, max_d))try:r = requests.get(u, headers=get_dynamic_headers(), timeout=15)d = parse_html_core(r.text); d['網址'] = ust.session_state['temp_results'].append(d)except:st.session_state['temp_results'].append({"網址": u, "結果": "失敗"})pbar.progress((i + 1) / len(urls))st.dataframe(pd.DataFrame(st.session_state['temp_results']))elif mode == "📂 異步解析":files = st.file_uploader("請上傳標案詳情 HTML", accept_multiple_files=True)if files and st.button("開始極速解析"):with concurrent.futures.ThreadPoolExecutor() as executor:res = list(executor.map(fast_file_processor, files))st.dataframe(pd.DataFrame(res))st.divider()st.markdown(f"**系統狀態**:歷史案號數 `{len(st.session_state['crawled_ids'])}`")
app.py+105-138