""" 取一章数据 """ import argparse import base64 import json import re import time from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait TARGET_PATTERNS = { "paragraphs": re.compile(r"/api/ancientlib/read/book/paragraphs/v2(?:\?|$)"), "pages": re.compile(r"/api/ancientlib/read/book/pages/v3/(?:\?|$)"), "word_box": re.compile(r"/api/ancientlib/read/word-box-page-content/m-get/(?:\?|$)"), "loader": re.compile(r"__loader=__session"), "volume": re.compile(r"/api/ancientlib/read/get/volume/(?:\?|$)"), } IMAGE_URL_RE = re.compile(r"https?://[^ ]+(?:\.webp|\.image|\.png|\.jpe?g|\.bmp)(?:\?.*)?$", re.IGNORECASE) def _safe_name(s: str) -> str: s = re.sub(r"[^a-zA-Z0-9._-]+", "_", s) return s[:180] if len(s) > 180 else s def _json_loads_maybe(data: str) -> Optional[Any]: try: return json.loads(data) except Exception: return None def _iter_strings(obj: Any) -> Iterable[str]: if isinstance(obj, str): yield obj return if isinstance(obj, list): for it in obj: yield from _iter_strings(it) return if isinstance(obj, dict): for v in obj.values(): yield from _iter_strings(v) def _extract_text_from_json(payload: Any) -> str: if not isinstance(payload, (dict, list)): return "" chunks: List[str] = [] def walk(o: Any) -> None: if isinstance(o, dict): for k, v in o.items(): lk = str(k).lower() if lk in {"text", "content", "paragraph", "para", "value", "word"} and isinstance(v, str): chunks.append(v) else: walk(v) elif isinstance(o, list): for it in o: walk(it) walk(payload) out = "\n".join(x.strip() for x in chunks if x and x.strip()) out = re.sub(r"\n{3,}", "\n\n", out) return out.strip() def _find_image_urls(payload: Any) -> List[str]: urls: List[str] = [] for s in _iter_strings(payload): if s.startswith("http") and (".webp" in s or ".image" in s or "/page/" in s): urls.append(s) dedup: List[str] = [] seen = set() for u in urls: if u not in seen: seen.add(u) dedup.append(u) return dedup def _maybe_decode_url(s: str) -> List[str]: if not isinstance(s, str) or len(s) < 16: return [] out: List[str] = [] try: raw = base64.b64decode(s, validate=False) txt = raw.decode("utf-8", errors="ignore") except Exception: return [] for m in re.finditer(r"https?://[^\\s\"']+", txt): u = m.group(0) if IMAGE_URL_RE.match(u) and ("byteimg.com" in u or "bytednsdoc.com" in u): out.append(u) return out def _extract_image_urls_from_pages(payload: Any) -> List[str]: urls: List[str] = [] if not isinstance(payload, dict): return urls data = payload.get("data") if not isinstance(data, dict): return urls pages = data.get("pages") if not isinstance(pages, list): return urls for p in pages: if not isinstance(p, dict): continue for key in ("picUrl", "thumbUrl"): v = p.get(key) if isinstance(v, str): urls.extend(_maybe_decode_url(v)) for v in p.values(): if isinstance(v, str) and IMAGE_URL_RE.match(v) and ("byteimg.com" in v or "bytednsdoc.com" in v): urls.append(v) return list(dict.fromkeys(urls)) def _guess_page_keys(payload: Any) -> List[Tuple[str, Any]]: hits: List[Tuple[str, Any]] = [] if isinstance(payload, dict): for k, v in payload.items(): lk = str(k).lower() if lk in {"pageid", "page_id", "page"} and isinstance(v, (str, int)): hits.append((str(k), v)) hits.extend(_guess_page_keys(v)) elif isinstance(payload, list): for it in payload: hits.extend(_guess_page_keys(it)) return hits @dataclass class CapturedResponse: kind: str url: str request_id: str status: int mime_type: str body_text: str def json(self) -> Optional[Any]: return _json_loads_maybe(self.body_text) def _make_driver(headless: bool) -> webdriver.Chrome: options = webdriver.ChromeOptions() if headless: options.add_argument("--headless=new") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("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") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option("useAutomationExtension", False) options.set_capability("goog:loggingPrefs", {"performance": "ALL"}) driver = webdriver.Chrome(options=options) driver.execute_cdp_cmd("Network.enable", {}) return driver def _drain_network( driver: webdriver.Chrome, tracked: Dict[str, Tuple[str, str, int, str]], ready: List[CapturedResponse], image_urls: List[str], img_dir: Path, max_images: int, img_saved: List[Dict[str, Any]], ) -> None: try: logs = driver.get_log("performance") except Exception: return for entry in logs: try: msg = json.loads(entry["message"])["message"] except Exception: continue method = msg.get("method") params = msg.get("params", {}) if method == "Network.requestWillBeSent": request = params.get("request", {}) url = request.get("url", "") if "00015" in url: print(f"[DEBUG] Network.requestWillBeSent for 00015: url={url}") if IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url): image_urls.append(url) elif method == "Network.responseReceived": response = params.get("response", {}) url = response.get("url", "") mime_type = str(response.get("mimeType", "") or "") if IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url): image_urls.append(url) request_id = params.get("requestId") if request_id and mime_type.startswith("image/") and IMAGE_URL_RE.match(url) and ("byteimg.com" in url or "bytednsdoc.com" in url): status = int(response.get("status", 0) or 0) tracked[request_id] = ("image", url, status, mime_type) print(f"[DEBUG] Tracked image response: request_id={request_id}, url={url}, status={status}") continue elif request_id and "00015" in url: print(f"[DEBUG] Found 00015 in url but didn't track as image. mime_type={mime_type}, url={url}, request_id={request_id}") kind = None for k, pat in TARGET_PATTERNS.items(): if pat.search(url): kind = k break if not kind: continue request_id = params.get("requestId") if not request_id: continue status = int(response.get("status", 0) or 0) tracked[request_id] = (kind, url, status, mime_type) elif method == "Network.loadingFinished": request_id = params.get("requestId") if not request_id or request_id not in tracked: continue kind, url, status, mime_type = tracked.pop(request_id) try: body = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id}) except Exception as e: if kind == "image": print(f"[DEBUG] Failed to get response body for image {url}: {e}") continue if kind == "image": if max_images > 0 and len(img_saved) >= max_images: print(f"[DEBUG] Max images reached, skipping {url}") continue raw = body.get("body", "") if not raw: print(f"[DEBUG] Empty body for image {url}") continue if body.get("base64Encoded"): try: data = base64.b64decode(raw) except Exception as e: print(f"[DEBUG] Failed to decode base64 for image {url}: {e}") continue else: data = raw.encode("utf-8", errors="ignore") ext = ".bin" if "webp" in (mime_type or "").lower(): ext = ".webp" elif "png" in (mime_type or "").lower(): ext = ".png" elif "jpeg" in (mime_type or "").lower() or "jpg" in (mime_type or "").lower(): ext = ".jpg" page_id = "" m = re.search(r"/page/([^/]+)/", url) if m: page_id = f"_{m.group(1)}" else: m2 = re.search(r"1k[a-z0-9]{11}", url) if m2: page_id = f"_{m2.group(0)}" # Default file name format file_name = f"{len(img_saved):04d}{page_id}{ext}" # Try to extract actual filename from URL, e.g. SWX0005_00001_00001.webp m_name = re.search(r"-([a-zA-Z0-9_]+\.(?:webp|png|jpe?g|jpg|bmp))", url, re.IGNORECASE) if m_name: file_name = m_name.group(1) else: m_name2 = re.search(r"/([^/]+?\.(?:webp|png|jpe?g|jpg|bmp))(?:[?~]|$)", url, re.IGNORECASE) if m_name2: name_part = m_name2.group(1) if "-" in name_part: file_name = name_part.split("-", 1)[-1] else: file_name = name_part out_path = img_dir / file_name try: out_path.write_bytes(data) print(f"[DEBUG] Saved image: {file_name} from {url}") except Exception as e: print(f"[DEBUG] Failed to save image {file_name} from {url}: {e}") continue img_saved.append({"url": url, "mimeType": mime_type, "path": str(out_path)}) continue body_text = body.get("body", "") if body.get("base64Encoded"): try: body_text = base64.b64decode(body_text).decode("utf-8", errors="replace") except Exception: body_text = "" if kind == "loader": try: data = json.loads(body_text) if "paragraphList" in data: para_payload = { "errorCode": 0, "errorMsg": "", "data": { "paragraphs": data["paragraphList"] } } body_text = json.dumps(para_payload, ensure_ascii=False) kind = "paragraphs" url = "https://www.shidianguji.com/api/ancientlib/read/book/paragraphs/v2?mock=from_loader" print(f"[DEBUG] Transformed loader response to paragraphs format") except Exception as e: print(f"[DEBUG] Failed to parse loader JSON: {e}") ready.append( CapturedResponse( kind=kind, url=url, request_id=request_id, status=status, mime_type=mime_type, body_text=body_text, ) ) def _collect_dom_image_urls(driver: webdriver.Chrome) -> List[str]: try: urls = driver.execute_script( "return Array.from(document.images||[]).map(i=>i.currentSrc||i.src).filter(Boolean);" ) except Exception: return [] if not isinstance(urls, list): return [] out: List[str] = [] for u in urls: if isinstance(u, str) and IMAGE_URL_RE.match(u) and ("byteimg.com" in u or "bytednsdoc.com" in u): out.append(u) return list(dict.fromkeys(out)) def _try_click_by_text(driver: webdriver.Chrome, text: str, timeout_s: float = 2.5) -> bool: xp = ( f"//*[self::button or self::a or @role='button' or self::div]" f"[contains(normalize-space(.), {json.dumps(text, ensure_ascii=False)})]" ) try: els = driver.find_elements(By.XPATH, xp) except Exception: return False for el in els[:5]: try: if not el.is_displayed() or not el.is_enabled(): continue el.click() return True except Exception: continue return False def _enter_image_mode(driver: webdriver.Chrome) -> None: for t in ("原图", "影印", "图片", "图像", "掃圖", "扫描", "切换"): if _try_click_by_text(driver, t, timeout_s=0): time.sleep(0.8) break def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--book-id", default="TPM0001") ap.add_argument("--chapter", default="新刻金瓶梅詞話卷之四[1]_第四十一回") # 因为目录有两个之四, 不写或者写 [0] 表示点击第一个(默认行为) 写 [1] 表示点击第二个 ap.add_argument("--out", default="out") ap.add_argument("--headless", action="store_true") ap.add_argument("--timeout", type=int, default=20000) ap.add_argument("--max-images", type=int, default=1000) args = ap.parse_args() out_dir = Path(args.out).resolve() raw_dir = out_dir / "raw" img_dir = out_dir / "images" coord_dir = out_dir / "coords" text_dir = out_dir / "text" for d in (raw_dir, img_dir, coord_dir, text_dir): d.mkdir(parents=True, exist_ok=True) driver = _make_driver(headless=args.headless) driver.set_window_size(1400, 900) captured: List[CapturedResponse] = [] tracked: Dict[str, Tuple[str, str, int, str]] = {} image_urls: List[str] = [] img_saved: List[Dict[str, Any]] = [] try: url = f"https://www.shidianguji.com/zh/book/{args.book_id}" driver.get(url) # Drain network to capture the initial chapter data for _ in range(5): time.sleep(1) before = len(captured) _drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved) if len(captured) == before and any(c.kind in ("paragraphs", "pages") for c in captured): break initial_captured = list(captured) initial_img_saved = list(img_saved) initial_image_urls = list(image_urls) captured.clear() img_saved.clear() image_urls.clear() tracked.clear() chapter_parts = args.chapter.split("_") current_part_idx = 0 clicked = False no_scroll_count = 0 for scroll_attempts in range(400): raw_target_part = chapter_parts[current_part_idx] # 解析可选的索引,例如 "新刻金瓶梅詞話卷之四[1]" 表示点击第2个匹配的元素(索引从0开始) target_part = raw_target_part target_index = 0 m_idx = re.search(r'\[(\d+)\]$', raw_target_part) if m_idx: target_index = int(m_idx.group(1)) target_part = raw_target_part[:m_idx.start()] part_clicked_in_this_attempt = False # 处理常见的异体字,如 "囘" 和 "回" search_parts = [target_part] if '囘' in target_part: search_parts.append(target_part.replace('囘', '回')) if '回' in target_part: search_parts.append(target_part.replace('回', '囘')) els = [] actual_part = target_part for sp in search_parts: try: # 寻找目标元素 els = driver.find_elements(By.XPATH, f"//*[contains(normalize-space(.), {json.dumps(sp, ensure_ascii=False)}) and not(.//*[contains(normalize-space(.), {json.dumps(sp, ensure_ascii=False)})])]") if not els: els = driver.find_elements(By.LINK_TEXT, sp) if not els: els = driver.find_elements(By.PARTIAL_LINK_TEXT, sp) if els: actual_part = sp break except Exception as e: print(f"[DEBUG] Exception finding '{sp}': {e}") pass target_part = actual_part try: # 为了调试,打印找到的元素数量 if els: print(f"[DEBUG] Found {len(els)} elements for '{target_part}'") for idx_debug, el_debug in enumerate(els): try: rect = driver.execute_script("return arguments[0].getBoundingClientRect();", el_debug) tag_name = el_debug.tag_name text_content = el_debug.text.strip() print(f"[DEBUG] Element {idx_debug}: tag={tag_name}, text='{text_content}', rect={rect}") except Exception as e: print(f"[DEBUG] Element {idx_debug}: Error getting info: {e}") seen_y_coords = [] for el in els: try: # 确保元素可见,但有时候框架中节点在视口外会被认为是 is_displayed() == False, # 可以先尝试滚动到视图内再判断。 driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el) time.sleep(0.3) # 某些特殊的折叠列表可能元素高度/宽度为0,我们通过 JS 获取位置和尺寸 rect = driver.execute_script("return arguments[0].getBoundingClientRect();", el) if rect['width'] <= 0 or rect['height'] <= 0: continue # 根据 Y 坐标去重,同一个位置的多个元素只算作一个匹配项 el_y = rect['top'] is_new_item = True for seen_y in seen_y_coords: if abs(seen_y - el_y) < 5: is_new_item = False break if is_new_item: seen_y_coords.append(el_y) # seen_y_coords 的长度就是当前发现了几个独立的视觉项 # 如果当前项的索引(长度-1)小于目标索引,则跳过 if len(seen_y_coords) - 1 < target_index: continue click_success = False try: # 如果元素有特殊的父级可点击区域,有时候点击自身会失败,尝试点击父级 # 在识典古籍中,目录经常是特定的 div 或者 span el.click() click_success = True except Exception: # Try JS click as fallback if standard click fails try: driver.execute_script("arguments[0].click();", el) click_success = True except Exception: pass # 如果点击成功了,我们需要检查它是不是实际上展开了。 # 因为在有些 UI 中,点击一个已经被选中的层级会把它折叠起来。 if click_success: print(f"[DEBUG] Clicked '{target_part}' successfully.") # 等待展开动画 time.sleep(1.5) # 判断是否成功展开:如果是父节点,我们需要能看到它的子节点 if current_part_idx < len(chapter_parts) - 1: raw_next_part = chapter_parts[current_part_idx + 1] next_part = raw_next_part m_next_idx = re.search(r'\[(\d+)\]$', raw_next_part) if m_next_idx: next_part = raw_next_part[:m_next_idx.start()] next_search_parts = [next_part] if '囘' in next_part: next_search_parts.append(next_part.replace('囘', '回')) if '回' in next_part: next_search_parts.append(next_part.replace('回', '囘')) next_els = [] actual_next_part = next_part for nsp in next_search_parts: next_els = driver.find_elements(By.XPATH, f"//*[contains(normalize-space(.), {json.dumps(nsp, ensure_ascii=False)}) and not(.//*[contains(normalize-space(.), {json.dumps(nsp, ensure_ascii=False)})])]") if not next_els: next_els = driver.find_elements(By.LINK_TEXT, nsp) if not next_els: next_els = driver.find_elements(By.PARTIAL_LINK_TEXT, nsp) if next_els: actual_next_part = nsp break is_next_visible = False for next_el in next_els: try: if driver.execute_script("var rect = arguments[0].getBoundingClientRect(); return rect.width > 0 && rect.height > 0;", next_el): is_next_visible = True break except: pass if not is_next_visible: print(f"[DEBUG] '{target_part}' was clicked but '{actual_next_part}' is still not visible. It might have been collapsed. Clicking again.") # 再点一次将其展开 try: el.click() except: driver.execute_script("arguments[0].click();", el) time.sleep(1.5) part_clicked_in_this_attempt = True if current_part_idx == len(chapter_parts) - 1: clicked = True else: current_part_idx += 1 no_scroll_count = 0 break except Exception as e: print(f"[DEBUG] Exception while interacting with '{target_part}': {e}") continue except Exception as e: print(f"[DEBUG] Exception finding '{target_part}': {e}") pass if clicked: break if part_clicked_in_this_attempt: continue # 如果没找到或没点击成功,滚动所有可滚动的 div,尝试让章节列表显示出来 try: scrolled = driver.execute_script(''' var els = document.querySelectorAll("div, ul, main, nav, section, aside"); var scrolledAny = false; for (var i = 0; i < els.length; i++) { var d = els[i]; if (d.scrollHeight > d.clientHeight && window.getComputedStyle(d).overflowY !== "hidden") { var before = d.scrollTop; d.scrollBy(0, 250); if (d.scrollTop > before) { scrolledAny = true; } } } return scrolledAny; ''') if not scrolled: no_scroll_count += 1 if no_scroll_count >= 20: print(f"[DEBUG] Reached the bottom of the list (tried 20 times). {target_part} not found.") break else: no_scroll_count = 0 except Exception: pass time.sleep(0.5) if clicked: print(f"[DEBUG] Clicked {args.chapter}, waiting for new network data...") # Wait until we see new 'paragraphs' or 'pages' in captured for _ in range(15): time.sleep(1) _drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved) if any(c.kind in ("paragraphs", "pages") for c in captured): print(f"[DEBUG] New data captured for {args.chapter}") break else: print(f"[DEBUG] {args.chapter} not clicked (not found).") has_new_data = any(c.kind in ("paragraphs", "pages") for c in captured) if not has_new_data: if clicked: print(f"[DEBUG] No new data loaded after clicking {args.chapter}. Using initial chapter data.") else: print(f"[DEBUG] Using initial chapter data because {args.chapter} was not found.") captured.extend(initial_captured) img_saved.extend(initial_img_saved) image_urls.extend(initial_image_urls) else: print(f"[DEBUG] Successfully loaded new chapter {args.chapter}. Merging missing data types from initial chapter data.") for kind in ("pages", "word_box", "volume", "paragraphs"): if not any(c.kind == kind for c in captured): print(f"[DEBUG] Inheriting {kind} from initial capture.") captured.extend([c for c in initial_captured if c.kind == kind]) # Keep initial images as they might be part of the same volume img_saved.extend(initial_img_saved) image_urls.extend(initial_image_urls) time.sleep(0.8) _enter_image_mode(driver) deadline = time.time() + max(10, int(args.timeout)) last_activity = time.time() no_activity_count = 0 print(f"Starting loop, deadline in {deadline - time.time()} seconds") # Try to find a scrollable container from selenium.webdriver.common.keys import Keys while time.time() < deadline: before_cap = len(captured) before_img = len(img_saved) _drain_network(driver, tracked, captured, image_urls, img_dir, int(args.max_images), img_saved) if len(captured) != before_cap or len(img_saved) != before_img: print(f"Activity! captured: {len(captured)} (+{len(captured)-before_cap}), img_saved: {len(img_saved)} (+{len(img_saved)-before_img})") last_activity = time.time() no_activity_count = 0 # Send PAGE_DOWN to body try: driver.find_element(By.TAG_NAME, "body").send_keys(Keys.PAGE_DOWN) except Exception: pass # Click next page if possible try: # The user indicated: