Install & Compatibility
Where this runs
tested against v0.2.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.648s · 22.8MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 2.3s · import 0.575s · 23MB
21MB installed
● package 21MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Browser
✓ import pychrome
browser = pychrome.Browser()
✗ from pychrome import Browser
The primary class `Browser` is intended to be accessed directly from the `pychrome` module, not imported directly, to maintain consistent API access.
Tab
✓ import pychrome
browser = pychrome.Browser()
tab = browser.new_tab()
Tab objects are created and managed by the Browser instance and are not directly instantiated by the user.
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.
import pychrome
import os
import subprocess
import time
# --- Step 1: Ensure Chrome is running with remote debugging enabled ---
# This command typically opens Chrome (or a headless instance) on port 9222.
# Adjust the path to your Chrome executable if needed.
# For headless mode: 'google-chrome --headless --disable-gpu --remote-debugging-port=9222'
# Check if Chrome is already running on the debug port
try:
# Attempt to connect to check if a browser is already listening
_ = pychrome.Browser(url="http://127.0.0.1:9222").list_tab()
print("Chrome with remote debugging already running.")
except Exception:
print("Starting Chrome with remote debugging...")
# Example for Linux/macOS. Adjust for Windows (e.g., 'start chrome.exe ...')
# Using os.environ.get for robustness in different environments
chrome_cmd = os.environ.get('CHROME_EXECUTABLE', 'google-chrome')
try:
# Start Chrome in headless mode for automation
subprocess.Popen([chrome_cmd, '--headless', '--disable-gpu', '--remote-debugging-port=9222'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(2) # Give Chrome a moment to start up
except FileNotFoundError:
print(f"Error: Chrome executable '{chrome_cmd}' not found. Please set CHROME_EXECUTABLE environment variable or ensure Chrome is in your PATH.")
exit(1)
# --- Step 2: Connect to Chrome and perform actions ---
browser = pychrome.Browser(url="http://127.0.0.1:9222")
# List existing tabs or create a new one
tabs = browser.list_tab()
if not tabs:
tab = browser.new_tab()
else:
# Use the first available tab, or iterate to find a specific one
tab = tabs[0]
def request_will_be_sent(**kwargs):
"""Callback function to print URLs of outgoing requests"""
url = kwargs.get('request', {}).get('url')
if url:
print(f" Loading: {url}")
try:
print(f"Interacting with tab: {tab.id}")
tab.start()
tab.Network.enable()
tab.Network.requestWillBeSent = request_will_be_sent # Register callback
print("Navigating to example.com...")
tab.Page.navigate(url="https://www.example.com", _timeout=5)
tab.wait(5) # Wait for page to load events for 5 seconds
# Execute some JavaScript on the page
result = tab.Runtime.evaluate(expression="document.title")
print(f"Page title: {result['result']['value']}")
finally:
# Clean up: stop the tab and close it
if tab:
tab.stop()
browser.close_tab(tab.id)
print(f"Closed tab: {tab.id}")
# In a real application, you might also want to close the browser process
# if it was started by your script, but care is needed not to close
# a user's active browser session.
Debug
Known issues
breakingBreaking 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.fixRegularly 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.
affects: All, but more frequent with major Chrome browser updates (e.g., Chrome v71 to v72, v108+, v111+).
gotchaThe 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.fixAlways 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.
affects: All versions of Chrome and pychrome.
gotchaIssues might arise when closing tabs or managing multiple tabs, sometimes leading to exceptions or zombie processes if not handled gracefully.fixAlways 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.
affects: All versions.
Upgrade
Version history
0.2.4latest on PyPI · released Jul 10, 2023
Audit
Dependencies
websocket-clientrequiredRequired for WebSocket communication with the Chrome DevTools Protocol.
requestsrequiredUsed for initial HTTP communication with the Chrome DevTools endpoint to list and create tabs.