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
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
"""
取一章数据
"""
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: <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())