# scraper.py ─ 2025-06-16 改版:支援 iframe 結果頁 import os, re, shutil, requests from bs4 import BeautifulSoup from urllib.parse import urljoin from playwright.sync_api import sync_playwright BASE = "https://judgment.judicial.gov.tw" # ---------- 共用工具 ---------- def log(msg: str, logfile: str): print(msg) with open(logfile, "a", encoding="utf-8") as f: f.write(msg + "\n") def shot(page, label, out_dir, log_file, always=False): """ 若 always=True 或 debug 模式才截圖 """ if not always and not page.context._debug: # 利用 Playwright context 自訂 flag return img = os.path.join(out_dir, f"{label}.png") page.screenshot(path=img) log(f"📸 截圖 {label}.png", log_file) def build_download_url(href: str) -> str: court = re.search(r"&id=([^&]+?)%2c", href).group(1) doc = re.search(r"%2c([^&]+?)&ot=in", href).group(1) return f"{BASE}/FILES/{court}/{doc}.pdf" def safe_filename(text: str, max_len=90): text = re.sub(r"[\\/:*?\"<>|]", "_", text) text = re.sub(r"\s+", "_", text).strip("_") return text[:max_len] # ---------- 主函式 ---------- def crawl(keyword: str, date_from: str, date_to: str, out_dir: str, debug: bool = False) -> str: y1, m1, d1 = date_from.split("-") y2, m2, d2 = date_to.split("-") os.makedirs(out_dir, exist_ok=True) log_path = os.path.join(out_dir, "debug.log") log(f"🚀 [{keyword}] {date_from}~{date_to} debug={debug}", log_path) with sync_playwright() as p: browser = p.chromium.launch( headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"] ) ctx = browser.new_context() ctx._debug = debug # 小旗標讓 shot() 能判斷 page = ctx.new_page() # 進入查詢表單 page.goto(f"{BASE}/FJUD/Default_AD.aspx", timeout=120_000) # 填表單 page.fill("#dy1", y1); page.fill("#dm1", m1); page.fill("#dd1", d1) page.fill("#dy2", y2); page.fill("#dm2", m2); page.fill("#dd2", d2) page.fill("#jud_kw", keyword) shot(page, "filled_form", out_dir, log_path, always=True) # 送出 page.click("#btnQry") # ★ 1) 先等 main-section 中的 iframe 出現 try: iframe_elem = page.wait_for_selector(".main-section iframe", timeout=120_000) except Exception: log("❌ 無法取得 iframe,可能被擋或查無資料", log_path) shot(page, "error_no_iframe", out_dir, log_path, always=True) browser.close() return log_path # ★ 2) 取得 iframe 的 src 並拼完整 URL iframe_src = iframe_elem.get_attribute("src") # 例:qryresultlst.aspx?ty=JUDBOOK&q=xxxx result_url = urljoin(f"{BASE}/FJUD/", iframe_src) # 組成 https://.../FJUD/qryresultlst.aspx?... log(f"➡️ 轉向結果頁:{result_url}", log_path) # 3) 轉向新 URL(同個 page) page.goto(result_url, timeout=120_000) shot(page, "result_top", out_dir, log_path, always=debug) # 4) 等待結果表 #jud try: page.wait_for_selector("#jud tr td a", timeout=120_000) except Exception: log("❌ #jud 仍未出現,停止", log_path) shot(page, "error_no_jud", out_dir, log_path, always=True) browser.close() return log_path # ---- 以下保持舊邏輯 ---- soup_top = BeautifulSoup(page.content(), "html.parser") count_span = soup_top.select_one("#result-count .badge") total = int(count_span.get_text(strip=True)) if count_span else 0 pages = (total + 19) // 20 if total else 1 log(f"📊 找到 {total} 筆,{pages} 頁", log_path) pdf_items = [] def parse_current_page(idx: int): soup = BeautifulSoup(page.content(), "html.parser") for tr in soup.select("#jud tr"): if tr.get("class") == ["summary"]: continue a_tag = tr.find("a") if not a_tag: continue tds = tr.find_all("td") if len(tds) < 4: continue pdf_items.append(( build_download_url(a_tag["href"]), a_tag.get_text(strip=True), tds[2].get_text(strip=True), tds[3].get_text(strip=True), )) shot(page, f"page_{idx}", out_dir, log_path, always=(debug or idx == 1)) parse_current_page(1) # 後續頁 for pno in range(2, pages + 1): next_url = f"{result_url}&Page={pno}" page.goto(next_url, timeout=120_000) parse_current_page(pno) log(f"📄 已解析第 {pno}/{pages} 頁", log_path) browser.close() # ---- 下載 PDF for url, title, date_txt, reason in pdf_items: fname = safe_filename(f"{keyword}-{title}-{date_txt}-{reason}") + ".pdf" fpath = os.path.join(out_dir, fname) try: r = requests.get(url, timeout=90) if r.status_code == 200: with open(fpath, "wb") as f: f.write(r.content) log(f"✔ 下載 {fname}", log_path) else: log(f"⚠️ 下載失敗 {url} ({r.status_code})", log_path) except Exception as e: log(f"❗ 下載例外 {url} err={e}", log_path) zip_path = shutil.make_archive(out_dir, "zip", out_dir) log(f"✅ 完成,ZIP:{zip_path}", log_path) return zip_path