import os import socket import subprocess import time CDP_PORT = 9222 CDP_URL = f"http://127.0.0.1:{CDP_PORT}" NO_PROXY = {"http": None, "https": None} for _k in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"): os.environ.pop(_k, None) CHROME_PATHS = [ r"C:\Program Files\Google\Chrome Beta\Application\chrome.exe", r"C:\Program Files\Google\Chrome\Application\chrome.exe", r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", os.path.join(os.environ.get("LOCALAPPDATA", ""), r"Google\Chrome\Application\chrome.exe"), os.path.join(os.environ.get("LOCALAPPDATA", ""), r"Google\Chrome Beta\Application\chrome.exe"), ] CHROME_USER_DATA = os.path.join(os.environ.get("LOCALAPPDATA", ""), r"Google\Chrome Beta\User Data") def set_cdp_port(port: int): global CDP_PORT, CDP_URL CDP_PORT = port CDP_URL = f"http://127.0.0.1:{CDP_PORT}" def _find_chrome(): for p in CHROME_PATHS: if os.path.exists(p): return p return None def _is_chrome_debug_running(): try: with socket.create_connection(("127.0.0.1", CDP_PORT), timeout=2): return True except (ConnectionRefusedError, OSError): return False def ensure_chrome_running(): if _is_chrome_debug_running(): print(f" Chrome 已在运行 (CDP port {CDP_PORT})") return True chrome_path = _find_chrome() if not chrome_path: print(" ERROR: 未找到 Chrome, 请手动启动:") print(f' chrome.exe --remote-debugging-port={CDP_PORT}') return False try: subprocess.run( ["powershell", "-Command", "Get-Process -Name chrome -ErrorAction SilentlyContinue | " "Where-Object { $_.Path -like '*Chrome Beta*' } | " "Stop-Process -Force"], capture_output=True, timeout=10, ) print(f" 已关闭 Chrome Beta 进程") time.sleep(3) except Exception: pass port_file = os.path.join(CHROME_USER_DATA, "DevToolsActivePort") try: if os.path.exists(port_file): os.remove(port_file) except Exception: pass print(f" 启动 Chrome Beta...") subprocess.run([ "powershell", "-Command", f'Start-Process "{chrome_path}" -ArgumentList ' f'"--remote-debugging-port={CDP_PORT}",' f'"--user-data-dir={CHROME_USER_DATA}",' f'"--no-first-run","--restore-last-session"' ], capture_output=True, timeout=10) for i in range(20): time.sleep(1) if _is_chrome_debug_running(): print(f" Chrome 已就绪 ({i+1}s)") return True print(f" ERROR: Chrome 启动超时, 请手动运行:") print(f' "{chrome_path}" --remote-debugging-port={CDP_PORT}') return False