playwright.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """
  2. Playwright 公共入口:项目根路径、NODE_OPTIONS、同步 API 与 browser_core 的 CDP 封装。
  3. 其它脚本请先保证项目根在 sys.path,再 `from workplace.playwright import ...`。
  4. """
  5. from __future__ import annotations
  6. import sys
  7. from contextlib import contextmanager
  8. from pathlib import Path
  9. from typing import Any, Iterator
  10. def ensure_repo_on_path() -> Path:
  11. """将项目根目录加入 sys.path。"""
  12. root = Path(__file__).resolve().parent.parent
  13. if str(root) not in sys.path:
  14. sys.path.insert(0, str(root))
  15. return root
  16. ensure_repo_on_path()
  17. from workplace.playwright_node_environment import ( # noqa: E402
  18. ensure_playwright_driver_node_options,
  19. )
  20. ensure_playwright_driver_node_options()
  21. from playwright.sync_api import sync_playwright # noqa: E402
  22. from workplace.cdp_chrome_browser_core import ( # noqa: E402
  23. _is_blank_url,
  24. connect_cdp,
  25. pick_target_page,
  26. repo_root,
  27. )
  28. DEFAULT_CDP_URL = "http://127.0.0.1:9222"
  29. def init_singleton() -> None:
  30. """
  31. 应用入口显式初始化:保证仓库在 path、Node/Playwright 驱动环境就绪。
  32. 不启动浏览器进程;可多次调用。
  33. """
  34. ensure_repo_on_path()
  35. ensure_playwright_driver_node_options()
  36. @contextmanager
  37. def sync_playwright_singleton() -> Iterator[Any]:
  38. """
  39. 单次自动化流程内共用一个 Playwright 同步实例:进入时 ``start()``,退出时 ``stop()``。
  40. 与 ``with sync_playwright() as p`` 等价,供 ``main.start`` 集中管理生命周期。
  41. """
  42. init_singleton()
  43. pw = sync_playwright().start()
  44. try:
  45. yield pw
  46. finally:
  47. pw.stop()
  48. def default_profile_dir() -> Path:
  49. return repo_root() / ".chrome-xhs-debug-profile"
  50. def connect_browser_via_cdp(
  51. playwright_inst,
  52. *,
  53. cdp: str | None = None,
  54. auto_chrome: bool = True,
  55. profile_dir: Path | None = None,
  56. ):
  57. """附着 CDP;缺省 CDP URL 与调试版 Chrome 用户目录同本仓库惯例。"""
  58. return connect_cdp(
  59. playwright_inst,
  60. cdp or DEFAULT_CDP_URL,
  61. auto_chrome=auto_chrome,
  62. profile_dir=profile_dir or default_profile_dir(),
  63. )