typst_hlm / ocr /getdata.py
dlxj
add ch80
1fff30f
Raw
History Blame Contribute Delete
29.3 kB
"""
取一章数据
"""
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())