{"id":8472,"library":"pychrome","title":"A Python Package for the Google Chrome Dev Protocol","description":"pychrome is a Python package designed for interacting with Google Chrome via the Chrome DevTools Protocol. It enables automation and inspection of web pages, allowing users to control browser behavior, capture network traffic, manipulate the DOM, and more. The current version is 0.2.4, with development actively maintained on GitHub.","status":"active","version":"0.2.4","language":"en","source_language":"en","source_url":"https://github.com/fate0/pychrome","tags":["web automation","chrome devtools protocol","headless browser","browser automation"],"install":[{"cmd":"pip install -U pychrome","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"Required for WebSocket communication with the Chrome DevTools Protocol.","package":"websocket-client","optional":false},{"reason":"Used for initial HTTP communication with the Chrome DevTools endpoint to list and create tabs.","package":"requests","optional":false}],"imports":[{"note":"The primary class `Browser` is intended to be accessed directly from the `pychrome` module, not imported directly, to maintain consistent API access.","wrong":"from pychrome import Browser","symbol":"Browser","correct":"import pychrome\nbrowser = pychrome.Browser()"},{"note":"Tab objects are created and managed by the Browser instance and are not directly instantiated by the user.","symbol":"Tab","correct":"import pychrome\nbrowser = pychrome.Browser()\ntab = browser.new_tab()"}],"quickstart":{"code":"import pychrome\nimport os\nimport subprocess\nimport time\n\n# --- Step 1: Ensure Chrome is running with remote debugging enabled ---\n# This command typically opens Chrome (or a headless instance) on port 9222.\n# Adjust the path to your Chrome executable if needed.\n# For headless mode: 'google-chrome --headless --disable-gpu --remote-debugging-port=9222'\n\n# Check if Chrome is already running on the debug port\ntry:\n    # Attempt to connect to check if a browser is already listening\n    _ = pychrome.Browser(url=\"http://127.0.0.1:9222\").list_tab()\n    print(\"Chrome with remote debugging already running.\")\nexcept Exception:\n    print(\"Starting Chrome with remote debugging...\")\n    # Example for Linux/macOS. Adjust for Windows (e.g., 'start chrome.exe ...')\n    # Using os.environ.get for robustness in different environments\n    chrome_cmd = os.environ.get('CHROME_EXECUTABLE', 'google-chrome')\n    try:\n        # Start Chrome in headless mode for automation\n        subprocess.Popen([chrome_cmd, '--headless', '--disable-gpu', '--remote-debugging-port=9222'],\n                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        time.sleep(2) # Give Chrome a moment to start up\n    except FileNotFoundError:\n        print(f\"Error: Chrome executable '{chrome_cmd}' not found. Please set CHROME_EXECUTABLE environment variable or ensure Chrome is in your PATH.\")\n        exit(1)\n\n# --- Step 2: Connect to Chrome and perform actions ---\nbrowser = pychrome.Browser(url=\"http://127.0.0.1:9222\")\n\n# List existing tabs or create a new one\ntabs = browser.list_tab()\nif not tabs:\n    tab = browser.new_tab()\nelse:\n    # Use the first available tab, or iterate to find a specific one\n    tab = tabs[0]\n\ndef request_will_be_sent(**kwargs):\n    \"\"\"Callback function to print URLs of outgoing requests\"\"\"\n    url = kwargs.get('request', {}).get('url')\n    if url:\n        print(f\"  Loading: {url}\")\n\ntry:\n    print(f\"Interacting with tab: {tab.id}\")\n    tab.start()\n    tab.Network.enable()\n    tab.Network.requestWillBeSent = request_will_be_sent # Register callback\n\n    print(\"Navigating to example.com...\")\n    tab.Page.navigate(url=\"https://www.example.com\", _timeout=5)\n    tab.wait(5) # Wait for page to load events for 5 seconds\n\n    # Execute some JavaScript on the page\n    result = tab.Runtime.evaluate(expression=\"document.title\")\n    print(f\"Page title: {result['result']['value']}\")\n\nfinally:\n    # Clean up: stop the tab and close it\n    if tab:\n        tab.stop()\n        browser.close_tab(tab.id)\n        print(f\"Closed tab: {tab.id}\")\n    # In a real application, you might also want to close the browser process\n    # if it was started by your script, but care is needed not to close \n    # a user's active browser session.\n","lang":"python","description":"This quickstart demonstrates how to connect to a running Chrome instance with remote debugging enabled, create a new tab, navigate to a URL, register a callback for network requests, and execute JavaScript to get the page title. It includes a robust way to ensure Chrome is running on the correct port before attempting to connect."},"warnings":[{"fix":"Regularly test your `pychrome` scripts against the target Chrome browser version. Consult `pychrome`'s GitHub issues for known incompatibilities. Consider pinning your Chrome browser version in automated environments.","message":"Breaking changes in Chrome browser versions can unexpectedly affect `pychrome`'s functionality, especially regarding the DevTools Protocol. Specific issues have been reported with changes to tab management and WebSocket connections after Chrome updates.","severity":"breaking","affected_versions":"All, but more frequent with major Chrome browser updates (e.g., Chrome v71 to v72, v108+, v111+)."},{"fix":"Always start Chrome with `google-chrome --remote-debugging-port=9222` (or `--headless --disable-gpu --remote-debugging-port=9222` for headless mode). Ensure the `url` parameter in `pychrome.Browser(url=...)` matches the specified port. Check if a browser process is already running and occupying the port.","message":"The Chrome browser must be launched with the remote debugging port enabled (e.g., `--remote-debugging-port=9222`) for `pychrome` to connect. Forgetting this flag or using an incorrect port will lead to connection failures.","severity":"gotcha","affected_versions":"All versions of Chrome and pychrome."},{"fix":"Always call `tab.stop()` before `browser.close_tab(tab.id)` and implement robust error handling (e.g., `try...finally` blocks) to ensure tabs are properly cleaned up, even if errors occur during page interaction. Consider using `browser.list_tab()` to verify tab state.","message":"Issues might arise when closing tabs or managing multiple tabs, sometimes leading to exceptions or zombie processes if not handled gracefully.","severity":"gotcha","affected_versions":"All versions."}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure Chrome is running with `--remote-debugging-port=9222` (or your chosen port). Verify the `url` parameter in `pychrome.Browser(url='http://127.0.0.1:9222')` matches. Check firewall settings or if another process is using the port.","cause":"The Chrome browser is not running with the remote debugging port enabled, or `pychrome` is trying to connect to the wrong IP address or port.","error":"requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))"},{"fix":"Update `pychrome` to the latest version (`pip install -U pychrome`). If the issue persists, try using an older, stable version of the Chrome browser that is known to be compatible with your `pychrome` version. Check GitHub issues for `pychrome` for specific reports related to your Chrome version.","cause":"This often indicates an incompatibility between the `pychrome` client and the Chrome DevTools Protocol version, or an issue with the Chrome instance itself, potentially due to a recent browser update.","error":"websocket._exceptions.WebSocketBadStatusException: Handshake status 400 Bad Request"},{"fix":"Verify that Chrome is properly started with the `--remote-debugging-port` flag and that no other application is interfering with the port. Restart Chrome. If the problem persists, this might be a browser version incompatibility; refer to `pychrome`'s GitHub issues for guidance or try a different Chrome version.","cause":"This error typically occurs when `pychrome` receives an unexpected, non-JSON response from the Chrome DevTools endpoint, often indicating a problem with the connection or the Chrome browser's debugging interface. This has been reported with specific Chrome versions.","error":"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"}]}