File size: 29,256 Bytes
519dd17 8fd4370 ae7dd0f 8fd4370 4f8f3f8 8fd4370 4f8f3f8 8fd4370 4f8f3f8 8fd4370 4f8f3f8 8fd4370 ae7dd0f 8fd4370 5d11e99 4f8f3f8 8fd4370 4f8f3f8 8fd4370 4f8f3f8 8fd4370 5d11e99 8fd4370 5d11e99 8fd4370 5d11e99 8fd4370 5d11e99 8fd4370 5d11e99 8fd4370 5d11e99 8fd4370 b14d9a8 62b2e1d 8fd4370 5d11e99 8fd4370 ae7dd0f 8fd4370 4f8f3f8 8fd4370 1fff30f 8fd4370 ef6325b b1a1afc 8fd4370 ae7dd0f 8fd4370 ae7dd0f 1350c49 f5ac12d 8fd4370 0b24249 7408a7c 0b24249 f5ac12d 0b24249 f5ac12d 0b24249 d46f137 1350c49 d46f137 1350c49 d46f137 f5ac12d d46f137 0b24249 d46f137 0b24249 d46f137 1350c49 f5ac12d 1350c49 0b24249 f5ac12d ae7dd0f d46f137 ae7dd0f d46f137 ae7dd0f 8fd4370 3c7bc46 b1a1afc 8fd4370 b1a1afc 8fd4370 b1a1afc 8fd4370 3c7bc46 b1a1afc 3c7bc46 b1a1afc 8fd4370 b1a1afc 3c7bc46 8fd4370 b1a1afc 4f8f3f8 8fd4370 b14d9a8 8fd4370 b14d9a8 8fd4370 b14d9a8 8fd4370 b14d9a8 8fd4370 4636cf0 8fd4370 4636cf0 8fd4370 192db92 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 | """
取一章数据
"""
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"),
}
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="SWX0005")
ap.add_argument("--chapter", default="第八十回")
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()
clicked = False
no_scroll_count = 0
for scroll_attempts in range(400):
try:
els = driver.find_elements(By.LINK_TEXT, args.chapter)
if not els:
els = driver.find_elements(By.PARTIAL_LINK_TEXT, args.chapter)
if not els:
xp = f"//*[contains(normalize-space(.), {json.dumps(args.chapter, ensure_ascii=False)}) and not(.//*[contains(normalize-space(.), {json.dumps(args.chapter, ensure_ascii=False)})])]"
els = driver.find_elements(By.XPATH, xp)
for el in els:
try:
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el)
time.sleep(0.2)
try:
el.click()
clicked = True
break
except Exception:
# Try JS click as fallback if standard click fails
driver.execute_script("arguments[0].click();", el)
clicked = True
break
except Exception:
continue
except Exception:
pass
if clicked:
break
# 如果没找到或没点击成功,滚动所有可滚动的 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). {args.chapter} 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}. Discarding initial chapter data.")
for img in initial_img_saved:
try:
Path(img["path"]).unlink(missing_ok=True)
except Exception as e:
print(f"[DEBUG] Failed to delete initial image {img['path']}: {e}")
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: <div class="vik-toolbox-btn click act" type="page-next">
next_btn = driver.find_element(By.XPATH, "//div[@type='page-next' or contains(@class, 'page-next') or contains(text(), '下一张')]")
# Add a small delay to prevent clicking too fast which might skip pages
# Check if we're not loading something
if next_btn.is_displayed():
# Check if button is disabled (has disable class)
cls = next_btn.get_attribute("class") or ""
if "disable" not in cls:
# Find current page text to ensure we only click once page changes
page_text_el = driver.find_elements(By.XPATH, "//div[contains(text(), '/')]")
curr_text = ""
for p in page_text_el:
if "/" in p.text:
curr_text = p.text
break
driver.execute_script("arguments[0].click();", next_btn)
# Wait for page to change
for _ in range(10):
time.sleep(0.2)
new_text = ""
for p in driver.find_elements(By.XPATH, "//div[contains(text(), '/')]"):
if "/" in p.text:
new_text = p.text
break
if new_text != curr_text:
break
except Exception:
pass
# Also try to scroll window and any potential scrollable divs
driver.execute_script('''
window.scrollBy(0, 900);
var divs = document.querySelectorAll("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].scrollHeight > divs[i].clientHeight && window.getComputedStyle(divs[i]).overflowY !== "hidden") {
divs[i].scrollBy(0, 900);
}
}
''')
time.sleep(0.6)
image_urls.extend(_collect_dom_image_urls(driver))
if time.time() - last_activity > 15:
no_activity_count += 1
print(f"No activity for 15 seconds (count: {no_activity_count}).")
if no_activity_count >= 3:
print("Too many consecutive periods of no activity, breaking loop.")
break
# Check if next button is actually disabled
try:
next_btn = driver.find_element(By.XPATH, "//div[@type='page-next' or contains(@class, 'page-next') or contains(text(), '下一张')]")
cls = next_btn.get_attribute("class") or ""
if "disable" in cls:
print("Reached end of chapter (next button disabled).")
break
else:
print("Next button not disabled, but no network activity. Try clicking again.")
driver.execute_script("arguments[0].click();", next_btn)
last_activity = time.time() - 10 # give it 5 more seconds before checking again
continue
except Exception:
print("Could not find next button, breaking loop.")
break
break
print(f"Loop finished. time.time() < deadline: {time.time() < deadline}")
for i, c in enumerate(captured):
ext = "json" if "json" in (c.mime_type or "") or c.body_text.strip().startswith("{") else "txt"
name = _safe_name(f"{i:04d}_{c.kind}_{c.status}_{c.url}")
(raw_dir / f"{name}.{ext}").write_text(c.body_text, encoding="utf-8", errors="replace")
img_urls = list(dict.fromkeys([u for u in image_urls if u.startswith("http")]))
pages_payloads = [c.json() for c in captured if c.kind == "pages" and c.status == 200]
page_id_to_hash = {}
for p in pages_payloads:
if p is not None:
img_urls.extend(_extract_image_urls_from_pages(p))
# Build pageId -> hash mapping
if isinstance(p, dict) and isinstance(p.get("data"), dict):
pages_list = p["data"].get("pages", [])
if isinstance(pages_list, list):
for page in pages_list:
if isinstance(page, dict):
pid = str(page.get("pageId", ""))
uri = str(page.get("uri", ""))
if pid and uri:
m = re.search(r"/page/([^/]+)/", uri)
if m:
page_id_to_hash[pid] = m.group(1)
else:
m2 = re.search(r"1k[a-z0-9]{11}", uri)
if m2:
page_id_to_hash[pid] = m2.group(0)
img_urls = list(dict.fromkeys(img_urls))
coords: Dict[str, Any] = {}
for c in captured:
if c.kind != "word_box" or c.status != 200:
continue
payload = c.json()
if payload is None:
continue
page_id = None
# Extract pageId directly from pageId2WordBoxContent if available
if isinstance(payload, dict) and isinstance(payload.get("data"), dict):
content = payload["data"].get("pageId2WordBoxContent")
if isinstance(content, dict) and content:
page_id = str(next(iter(content.keys())))
if not page_id:
page_keys = _guess_page_keys(payload)
for _, v in page_keys:
if isinstance(v, (str, int)):
page_id = str(v)
break
hash_suffix = ""
if page_id and page_id in page_id_to_hash:
hash_suffix = f"_{page_id_to_hash[page_id]}"
key = f"wordbox_{len(coords):04d}{hash_suffix}"
coords[key] = payload
(coord_dir / f"{_safe_name(key)}.json").write_text(
json.dumps(payload, ensure_ascii=False),
encoding="utf-8",
errors="replace",
)
paragraph_texts: List[str] = []
for c in captured:
if c.kind != "paragraphs" or c.status != 200:
continue
payload = c.json()
if payload is None:
continue
t = _extract_text_from_json(payload)
if t:
paragraph_texts.append(t)
full_text = "\n\n".join(paragraph_texts).strip()
if not full_text and coords:
fallback_chunks: List[str] = []
for v in coords.values():
t = _extract_text_from_json(v)
if t:
fallback_chunks.append(t)
full_text = "\n\n".join(fallback_chunks).strip()
if full_text:
(text_dir / "text.txt").write_text(full_text, encoding="utf-8", errors="replace")
summary = {
"bookId": args.book_id,
"chapter": args.chapter,
"captured": [
{"kind": c.kind, "status": c.status, "mimeType": c.mime_type, "url": c.url}
for c in captured
],
"imageUrls": img_urls[: max(0, int(args.max_images))],
"imagesSaved": img_saved,
"coords_keys": list(coords.keys()),
"out": str(out_dir),
}
(out_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
return 0
finally:
try:
driver.quit()
from gendatav2 import do_gendata
do_gendata()
except Exception:
pass
if __name__ == "__main__":
raise SystemExit(main())
|