38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
"""chrome helper: ensure chrome with CDP is running."""
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
|
|
CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
|
|
|
|
|
|
def _up(port):
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:%d/json/version" % port, timeout=2) as r:
|
|
return json.loads(r.read().decode())
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def ensure(port=9242, prof=r"C:\Users\User\tmp\camb\prof2", extra=None):
|
|
v = _up(port)
|
|
if v:
|
|
return v
|
|
os.makedirs(prof, exist_ok=True)
|
|
args = [CHROME, "--remote-debugging-port=%d" % port, "--user-data-dir=" + prof,
|
|
"--no-first-run", "--no-default-browser-check",
|
|
"--disable-blink-features=AutomationControlled",
|
|
"--window-size=1280,1000"]
|
|
if extra:
|
|
args += extra
|
|
args.append("about:blank")
|
|
subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)
|
|
for _ in range(30):
|
|
time.sleep(1)
|
|
v = _up(port)
|
|
if v:
|
|
return v
|
|
raise RuntimeError("chrome failed to start on %d" % port) |