har_capture.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. """Record a HAR file while driving a website with Playwright.
  3. Usage:
  4. python3 har_capture.py <url> <output.har> [--wait SECONDS] \
  5. [--action "fill:SELECTOR:TEXT"] [--action "press:SELECTOR:KEY"] \
  6. [--action "click:SELECTOR"] [--action "goto:URL"] [--action "sleep:SECONDS"]
  7. Actions run in order after page load. The HAR embeds request/response bodies
  8. (record_har_content='embed') so derived clients can see payload shapes.
  9. NOTE: a failing action raises before the HAR is flushed -- you get no file.
  10. Fix the selector (try --headed to watch) and rerun.
  11. """
  12. import argparse
  13. import sys
  14. import time
  15. from playwright.sync_api import sync_playwright
  16. def run_action(page, spec: str) -> None:
  17. parts = spec.split(":", 2)
  18. kind = parts[0]
  19. if kind == "fill":
  20. page.fill(parts[1], parts[2])
  21. elif kind == "press":
  22. page.press(parts[1], parts[2])
  23. elif kind == "click":
  24. page.click(parts[1])
  25. elif kind == "goto":
  26. page.goto(parts[1] + (":" + parts[2] if len(parts) > 2 else ""))
  27. elif kind == "sleep":
  28. time.sleep(float(parts[1]))
  29. else:
  30. raise ValueError(f"unknown action: {spec}")
  31. def main() -> int:
  32. ap = argparse.ArgumentParser()
  33. ap.add_argument("url")
  34. ap.add_argument("har_path")
  35. ap.add_argument("--wait", type=float, default=3.0,
  36. help="seconds to idle at the end so late XHRs land in the HAR")
  37. ap.add_argument("--action", action="append", default=[],
  38. help="fill:SEL:TEXT | press:SEL:KEY | click:SEL | goto:URL | sleep:SECS")
  39. ap.add_argument("--headed", action="store_true")
  40. args = ap.parse_args()
  41. with sync_playwright() as p:
  42. browser = p.chromium.launch(channel="chromium", headless=not args.headed)
  43. context = browser.new_context(
  44. record_har_path=args.har_path,
  45. record_har_content="embed", # keep response bodies in the HAR
  46. )
  47. page = context.new_page()
  48. page.goto(args.url, wait_until="domcontentloaded")
  49. for spec in args.action:
  50. run_action(page, spec)
  51. try:
  52. page.wait_for_load_state("networkidle", timeout=15000)
  53. except Exception:
  54. pass # some pages never fully idle; the trailing --wait covers it
  55. time.sleep(args.wait)
  56. context.close() # flushes the HAR
  57. browser.close()
  58. print(f"HAR written: {args.har_path}")
  59. return 0
  60. if __name__ == "__main__":
  61. sys.exit(main())