from __future__ import annotations import os from pathlib import Path def playwright_browsers_root() -> Path | None: local_appdata = os.environ.get("LOCALAPPDATA", "").strip() if not local_appdata: return None return Path(local_appdata) / "ms-playwright" def configure_playwright_runtime_env() -> Path | None: root = playwright_browsers_root() if root is None: return None if root.exists() and "PLAYWRIGHT_BROWSERS_PATH" not in os.environ: os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(root) return root def preferred_chromium_executable() -> Path | None: root = configure_playwright_runtime_env() if root is None or not root.exists(): return None candidates: list[tuple[int, float, Path]] = [] for browser_dir in root.glob("chromium-*"): if not browser_dir.is_dir(): continue revision = _parse_revision(browser_dir.name) for relative in ( Path("chrome-win64") / "chrome.exe", Path("chrome-win") / "chrome.exe", ): executable = browser_dir / relative if executable.is_file(): try: mtime = executable.stat().st_mtime except OSError: mtime = 0.0 candidates.append((revision, mtime, executable)) break if not candidates: return None candidates.sort(key=lambda item: (item[0], item[1]), reverse=True) return candidates[0][2] def explain_missing_browser(exc: Exception, *, feature_name: str) -> str: text = str(exc) lowered = text.lower() if "executable doesn't exist" not in lowered and "browsertype.launch_persistent_context" not in lowered: return text return ( f"{feature_name} 需要 Playwright Chromium 浏览器,但当前系统里没有可用的浏览器文件。\n" "请先运行同目录下的 install_playwright_chromium.bat,安装完成后重新打开程序再试。" ) def _parse_revision(name: str) -> int: try: return int(name.rsplit("-", 1)[-1]) except (TypeError, ValueError): return 0