# -*- coding: utf-8 -*- """CDP driver v4: supports 'inject' step that pastes a value before eval.""" import json, sys, asyncio, io import websockets WS = None console_msgs = [] page_errors = [] pending = {} _id = [0] async def connect(target_url_sub): global WS import urllib.request data = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json").read().decode()) page = [t for t in data if t.get("type") == "page" and target_url_sub in t.get("url", "")] if not page: page = [t for t in data if t.get("type") == "page"] WS = await websockets.connect(page[0]["webSocketDebuggerUrl"], max_size=50*1024*1024) async def send(method, params=None): _id[0] += 1 msg = {"id": _id[0], "method": method} if params: msg["params"] = params await WS.send(json.dumps(msg)) return _id[0] async def recv_loop(): try: while True: raw = await WS.recv() msg = json.loads(raw) m = msg.get("method", "") if m == "Runtime.consoleAPICalled": args = [a.get("value", a.get("description", "")) for a in msg["params"].get("args", [])] console_msgs.append((msg["params"].get("type", "log"), " ".join(str(a) for a in args)[:1000])) elif m == "Runtime.exceptionThrown": d = msg["params"]["exceptionDetails"] txt = d.get("exception", {}).get("description") or d.get("text", "") page_errors.append(txt[:1000]) elif "id" in msg and msg["id"] in pending: fut = pending.pop(msg["id"]) if not fut.done(): fut.set_result(msg) except Exception as e: console_msgs.append(("driver-error", str(e))) async def wait_for(rid, timeout=25): loop = asyncio.get_event_loop() fut = loop.create_future() pending[rid] = fut return await asyncio.wait_for(fut, timeout) async def eval_js(expr, await_promise=False, timeout=25): rid = await send("Runtime.evaluate", {"expression": expr, "returnByValue": True, "awaitPromise": await_promise}) resp = await wait_for(rid, timeout) r = resp.get("result", {}) if r.get("exceptionDetails"): return {"__error__": (r["exceptionDetails"].get("exception", {}) or {}).get("description") or r["exceptionDetails"].get("text", "")} return r.get("result", {}).get("value") async def main(script, dbg_token): await connect("127.0.0.1:98") recv_task = asyncio.create_task(recv_loop()) rid = await send("Runtime.enable"); await wait_for(rid, 10) rid = await send("Page.enable"); await wait_for(rid, 10) for step in script: kind = step.get("op", "eval") if kind == "sleep": await asyncio.sleep(step["ms"] / 1000) continue if kind == "nav": rid = await send("Page.navigate", {"url": "http://127.0.0.1:98/"}) await wait_for(rid, 15) continue expr = step["expr"].replace("window.__DBG_TOKEN__", json.dumps(dbg_token)) try: val = await eval_js(expr, await_promise=step.get("await", False)) except Exception as e: val = {"__driver_error__": str(e)} print("STEP", step.get("label", ""), "=>", json.dumps(val, ensure_ascii=False, default=str)[:2500]) await asyncio.sleep(1.2) print("\n=== CONSOLE ===") for t, m in console_msgs[-120:]: print(f"[{t}] {m}") print("\n=== PAGE ERRORS ===") for e in page_errors[-40:]: print(e) recv_task.cancel() if __name__ == "__main__": with io.open(sys.argv[1], "r", encoding="utf-8") as f: script = json.load(f) token = io.open(sys.argv[2], "r", encoding="utf-8").read().strip() asyncio.run(main(script, token))