Spaces:
Runtime error
Runtime error
Download scraper.py from htchu/WeatherLRDDemo: direct link, hf CLI and curl.
- Browser
- Download file 8.87 kB
-
https://huggingface.co/spaces/htchu/WeatherLRDDemo/resolve/main/scraper.py
- Command line
-
hf download hf://spaces/htchu/WeatherLRDDemo/scraper.py
-
curl -L -o scraper.py https://huggingface.co/spaces/htchu/WeatherLRDDemo/resolve/main/scraper.py
8.87 kB
| """ | |
| 環境部主管法規爬蟲 | |
| 從 https://oaout.moenv.gov.tw/law/ 爬取所有法規內容 | |
| """ | |
| import requests | |
| import urllib3 | |
| from bs4 import BeautifulSoup | |
| # 環境部網站 SSL 憑證有問題,需停用驗證 | |
| urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) | |
| import json | |
| import time | |
| import os | |
| import re | |
| from pathlib import Path | |
| BASE_URL = "https://oaout.moenv.gov.tw/law" | |
| CATEGORIES = [ | |
| {"id": "1501", "name": "環境綜合計畫"}, | |
| {"id": "1502", "name": "公害糾紛處理"}, | |
| {"id": "1503", "name": "綠色生活"}, | |
| {"id": "1504", "name": "績效管理"}, | |
| {"id": "1505", "name": "國際合作"}, | |
| {"id": "1601", "name": "環境綜合管理"}, | |
| {"id": "1602", "name": "環境教育"}, | |
| {"id": "1603", "name": "環境影響評估"}, | |
| {"id": "1701", "name": "空氣品質管理"}, | |
| {"id": "1702", "name": "固定源空污防制"}, | |
| {"id": "1703", "name": "移動源空污防制"}, | |
| {"id": "1704", "name": "室內空氣品質管理"}, | |
| {"id": "1705", "name": "噪音與電磁波管理"}, | |
| {"id": "1706", "name": "空氣品質監測"}, | |
| {"id": "1801", "name": "水污染防治"}, | |
| {"id": "1802", "name": "飲用水管理"}, | |
| {"id": "1903", "name": "組織處務(資訊科技)"}, | |
| {"id": "1901", "name": "資料治理"}, | |
| {"id": "1902", "name": "資訊安全"}, | |
| {"id": "2001", "name": "組織處務(氣候變遷)"}, | |
| {"id": "2002", "name": "氣候變遷因應"}, | |
| {"id": "2101", "name": "組織處務(資源循環)"}, | |
| {"id": "2106", "name": "資源回收再利用"}, | |
| {"id": "2107", "name": "廢棄物清理"}, | |
| {"id": "2108", "name": "應回收廢棄物管理"}, | |
| {"id": "2201", "name": "組織處務(化學物質)"}, | |
| {"id": "2202", "name": "毒性及關注化學物質管理"}, | |
| {"id": "2203", "name": "環境用藥管理"}, | |
| {"id": "2301", "name": "組織處務(環境管理)"}, | |
| {"id": "2302", "name": "公害陳情與督察"}, | |
| {"id": "2303", "name": "生活廢棄物處理"}, | |
| {"id": "2304", "name": "環境影響評估監督"}, | |
| {"id": "2305", "name": "清潔人員照護"}, | |
| {"id": "2306", "name": "環境衛生"}, | |
| {"id": "2307", "name": "土壤及地下水"}, | |
| {"id": "2401", "name": "組織處務(國家環境研究)"}, | |
| {"id": "2402", "name": "環境污染檢驗"}, | |
| {"id": "2403", "name": "環保人員訓練"}, | |
| {"id": "2404", "name": "環境教育認證"}, | |
| {"id": "25", "name": "秘書"}, | |
| {"id": "26", "name": "人事"}, | |
| {"id": "27", "name": "政風"}, | |
| {"id": "28", "name": "會計"}, | |
| {"id": "29", "name": "統計"}, | |
| {"id": "30", "name": "法制"}, | |
| ] | |
| HEADERS = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", | |
| "Accept-Language": "zh-TW,zh;q=0.9,en;q=0.8", | |
| } | |
| def get_session(): | |
| session = requests.Session() | |
| session.headers.update(HEADERS) | |
| session.verify = False # 該網站 SSL 憑證有問題,需跳過驗證 | |
| return session | |
| def get_law_list_page(session, category_id, page=1, size=40): | |
| """取得某分類某頁的法規列表""" | |
| url = f"{BASE_URL}/LawCategoryMain.aspx" | |
| params = {"CategoryID": category_id, "page": page, "size": size} | |
| resp = session.get(url, params=params, timeout=30) | |
| resp.encoding = "utf-8" | |
| return resp.text | |
| def parse_law_list(html): | |
| """從分類頁面解析法規列表,回傳法規ID與名稱""" | |
| soup = BeautifulSoup(html, "html.parser") | |
| laws = [] | |
| # 找所有連結到 LawContent.aspx 的 <a> 標籤 | |
| for link in soup.find_all("a", href=re.compile(r"LawContent\.aspx\?id=")): | |
| href = link.get("href", "") | |
| match = re.search(r"id=([A-Za-z0-9]+)", href) | |
| if match: | |
| law_id = match.group(1) | |
| law_name = link.get_text(strip=True) | |
| if law_name: | |
| laws.append({"id": law_id, "name": law_name}) | |
| return laws | |
| def get_total_pages(html): | |
| """解析總頁數""" | |
| soup = BeautifulSoup(html, "html.parser") | |
| text = soup.get_text() | |
| # 尋找 "頁次:1/2" 格式 | |
| match = re.search(r"頁次[::]\s*(\d+)\s*/\s*(\d+)", text) | |
| if match: | |
| return int(match.group(2)) | |
| return 1 | |
| def get_law_content(session, law_id): | |
| """取得單一法規的完整內容""" | |
| url = f"{BASE_URL}/LawContent.aspx?id={law_id}" | |
| resp = session.get(url, timeout=30) | |
| resp.encoding = "utf-8" | |
| return parse_law_content(resp.text, law_id) | |
| def parse_law_content(html, law_id): | |
| """解析法規內容頁面""" | |
| soup = BeautifulSoup(html, "html.parser") | |
| result = {"id": law_id, "title": "", "publish_date": "", "content": ""} | |
| # 取得法規名稱 - 通常在 <h2> 或頁面標題中 | |
| title_tag = soup.find("h2") | |
| if title_tag: | |
| result["title"] = title_tag.get_text(strip=True) | |
| else: | |
| title_tag = soup.find("title") | |
| if title_tag: | |
| result["title"] = title_tag.get_text(strip=True) | |
| # 嘗試取得發布日期 | |
| for text in soup.stripped_strings: | |
| date_match = re.search(r"民國\s*(\d+)\s*年\s*(\d+)\s*月\s*(\d+)\s*日", text) | |
| if date_match: | |
| result["publish_date"] = date_match.group(0) | |
| break | |
| # 取得主要內容區域 | |
| # 嘗試多種選擇器來找到內容 | |
| content_area = ( | |
| soup.find("div", {"id": re.compile(r"content|lawcontent|main", re.I)}) | |
| or soup.find("div", class_=re.compile(r"content|law", re.I)) | |
| or soup.find("main") | |
| ) | |
| if content_area: | |
| result["content"] = content_area.get_text("\n", strip=True) | |
| else: | |
| # 備用方案:取得 body 主要文字內容(排除導航等) | |
| body = soup.find("body") | |
| if body: | |
| # 移除 script, style, nav, header, footer | |
| for tag in body.find_all(["script", "style", "nav", "header", "footer"]): | |
| tag.decompose() | |
| result["content"] = body.get_text("\n", strip=True) | |
| return result | |
| def scrape_category(session, category): | |
| """爬取整個分類的所有法規""" | |
| cat_id = category["id"] | |
| cat_name = category["name"] | |
| print(f"\n{'='*60}") | |
| print(f"正在爬取分類: {cat_name} (ID: {cat_id})") | |
| all_laws = [] | |
| # 第一頁(同時取得總頁數) | |
| html = get_law_list_page(session, cat_id, page=1, size=40) | |
| total_pages = get_total_pages(html) | |
| laws_on_page = parse_law_list(html) | |
| all_laws.extend(laws_on_page) | |
| print(f" 共 {total_pages} 頁") | |
| # 後續頁面 | |
| for page in range(2, total_pages + 1): | |
| time.sleep(0.5) | |
| html = get_law_list_page(session, cat_id, page=page, size=40) | |
| laws_on_page = parse_law_list(html) | |
| all_laws.extend(laws_on_page) | |
| print(f" 找到 {len(all_laws)} 筆法規") | |
| # 爬取每筆法規的內容 | |
| law_contents = [] | |
| for i, law in enumerate(all_laws): | |
| time.sleep(0.3) # 禮貌性延遲 | |
| try: | |
| content = get_law_content(session, law["id"]) | |
| content["category_id"] = cat_id | |
| content["category_name"] = cat_name | |
| if not content["title"]: | |
| content["title"] = law["name"] | |
| law_contents.append(content) | |
| print(f" [{i+1}/{len(all_laws)}] {law['name']}") | |
| except Exception as e: | |
| print(f" [{i+1}/{len(all_laws)}] 錯誤: {law['name']} - {e}") | |
| return law_contents | |
| def main(): | |
| output_dir = Path("data") | |
| output_dir.mkdir(exist_ok=True) | |
| session = get_session() | |
| all_laws = [] | |
| for category in CATEGORIES: | |
| try: | |
| laws = scrape_category(session, category) | |
| all_laws.extend(laws) | |
| except Exception as e: | |
| print(f"分類 {category['name']} 爬取失敗: {e}") | |
| # 每個分類爬完後暫存 | |
| time.sleep(1) | |
| # 儲存完整 JSON | |
| output_file = output_dir / "moenv_laws.json" | |
| with open(output_file, "w", encoding="utf-8") as f: | |
| json.dump(all_laws, f, ensure_ascii=False, indent=2) | |
| print(f"\n完成!共爬取 {len(all_laws)} 筆法規,儲存至 {output_file}") | |
| # 同時產生純文字版本供 RAG 使用 | |
| txt_dir = output_dir / "laws_txt" | |
| txt_dir.mkdir(exist_ok=True) | |
| for law in all_laws: | |
| safe_name = re.sub(r'[\\/*?:"<>|]', "_", law["title"][:80]) if law["title"] else law["id"] | |
| txt_file = txt_dir / f"{law['id']}_{safe_name}.txt" | |
| with open(txt_file, "w", encoding="utf-8") as f: | |
| f.write(f"法規名稱: {law['title']}\n") | |
| f.write(f"分類: {law['category_name']}\n") | |
| f.write(f"發布日期: {law['publish_date']}\n") | |
| f.write(f"法規ID: {law['id']}\n") | |
| f.write(f"{'='*40}\n") | |
| f.write(law["content"]) | |
| print(f"純文字檔案已儲存至 {txt_dir}/") | |
| if __name__ == "__main__": | |
| main() | |