ddp_utils.browser.cdp¶
import ddp_utils.browser.cdp
Own unified facade CDP and native Chromium CDP transports.
- class ddp_utils.browser.cdp.BrowserCDP(browser: Browser)¶
Bases:
objectExpose raw Chrome DevTools Protocol access where it exists.
Parameters
Name
Type
Description
browser
Owning browser facade.
Examples
Execute a raw command only after checking availability:
if browser.cdp.available: result = browser.cdp.cmd("Network.enable").require()
Bind lazy CDP sessions to one browser lifecycle.
Parameters
Name
Type
Description
browser
Owning browser facade.
Examples
Browser creates this service once:
cdp = BrowserCDP(browser)
- property available: bool¶
Return whether the active backend declares CDP support.
Returns
Truefor supported Chromium automation sessions.Examples
Guard provider-specific protocol logic:
if browser.cdp.available: enable_network()
- property mode: str | None¶
Return the active normalized CDP transport mode.
Returns
webdriverorplaywright-session; otherwiseNone.Examples
Record which transport produced diagnostics:
print(browser.cdp.mode)
- cmd(method: str, params: dict[str, Any] | None = None, *, required: bool = False) CapabilityResult[Any]¶
Execute one raw CDP command.
Parameters
Name
Type
Description
method
str
Fully qualified CDP method.
params
dict[str, Any] | None
Optional command parameters.
required
bool
Raise instead of returning a soft unsupported result.
Returns
Type
Description
CapabilityResult[Any]
Structured supported or unsupported command result.
Raises
Exception
Description
A supported backend rejects the command.
CDP is required but unavailable.
Examples
Read browser version metadata:
version = browser.cdp.cmd("Browser.getVersion", required=True).require()
- on(event: str, callback: Callable[[...], Any]) CapabilityResult[BrowserSubscription]¶
Subscribe to one raw CDP event.
Parameters
Name
Type
Description
event
str
Fully qualified CDP event name.
callback
Callable[[...], Any]
Callable receiving provider event payloads.
Returns
Type
Description
Subscription capability result.
Raises
Exception
Description
Listener installation fails.
Listening is required but unavailable.
Examples
Observe response events:
subscription = browser.cdp.on( "Network.responseReceived", callback ).require()
- off(subscription: BrowserSubscription) None¶
Remove one CDP event subscription idempotently.
Parameters
Name
Type
Description
subscription
Subscription returned by
on().Raises
Exception
Description
Provider listener removal fails.
Examples
Stop receiving response events:
browser.cdp.off(subscription)
- session(target: Any | None = None) CapabilityResult[Any]¶
Return the raw active CDP transport object.
Parameters
Name
Type
Description
target
Any | None
Optional Playwright page or facade page descriptor.
Returns
Type
Description
CapabilityResult[Any]
Raw session capability result. Selenium returns WebDriver because
execute_cdp_cmdis its transport boundary.Examples
Access a Playwright CDP session deliberately:
raw = browser.cdp.session().require()
- close() None¶
Remove listeners and detach the owned Playwright CDP session.
Examples
Browser lifecycle cleanup calls this automatically:
browser.cdp.close()
- class ddp_utils.browser.cdp.CDPConnection(websocket_connection: Any)¶
Bases:
objectThread-safe synchronous connection to one Chromium CDP target.
Examples
Use this public operation:
instance = CDPConnection(websocket_connection)
Bind an open websocket-client connection.
Parameters
Name
Type
Description
websocket_connection
Any
Open websocket-client connection to the CDP target.
- command(method: str, params: Mapping[str, Any] | None = None) Mapping[str, Any]¶
Execute an arbitrary CDP command and return its result object.
The call is serialized with other commands on this connection. Protocol events received while waiting for the matching response are discarded.
Parameters
Name
Type
Description
method
str
Fully qualified CDP method name, such as
Browser.getVersion.params
Mapping[str, Any] | None
Optional JSON-serializable command parameters.
Nonesends an empty parameter mapping.Returns
Type
Description
Mapping[str, Any]
A new dictionary containing the command’s CDP result object.
Raises
Exception
Description
The connection closes, Chromium reports a protocol error, or the response does not contain a mapping result.
TypeError
The supplied parameters are not JSON serializable.
Examples
Query version metadata through an open connection:
result = connection.command("Browser.getVersion") product = result["product"]
- evaluate(expression: str, *, await_promise: bool = False) Any¶
Evaluate JavaScript in the page and return a JSON-compatible value.
Parameters
Name
Type
Description
expression
str
JavaScript source evaluated in the attached page.
await_promise
bool
Wait for a returned promise to settle when
True.Returns
Type
Description
Any
The value copied from Chromium’s remote result, or
Nonewhen the expression produces no serializable value.Raises
Exception
Description
The command fails, JavaScript raises an exception, or the protocol response omits the expected remote result.
Examples
Read the current document title:
title = connection.evaluate("document.title")
- close() None¶
Close the underlying websocket connection.
Examples
Use this public operation:
result = c_d_p_connection.close()
- exception ddp_utils.browser.cdp.CDPError(message: str, *, details: Any = None)¶
Bases:
RuntimeErrorDescribe a local Chrome DevTools Protocol failure.
Examples
Use this public operation:
instance = CDPError(message)
Create an error while retaining optional protocol details.
Parameters
Name
Type
Description
message
str
Error text.
details
Any
Optional protocol details kept on the exception.
- class ddp_utils.browser.cdp.ChromiumInstallation(browser: str, path: Path)¶
Bases:
objectDescribe one detected Chromium-family browser executable.
Examples
Use this public operation:
instance = ChromiumInstallation()
- class ddp_utils.browser.cdp.ChromiumProfile(browser: str, user_data_dir: Path, profile_directory: str = 'Default', unpacked_extensions: tuple[Path, ...] = (), generated: bool = False, copy_report: ChromiumProfileCopyReport | None = None)¶
Bases:
objectDescribe one Chromium user-data directory and profile subdirectory.
Variables
Name
Type
Description
browser
str
Normalized Chromium product name.
user_data_dir
pathlib.Path
Absolute root containing the product’s profile data.
profile_directory
str
Profile subdirectory name, or
.when the root itself is the profile directory.unpacked_extensions
tuple[pathlib.Path, ...]
Absolute unpacked-extension directories associated with this profile.
generated
bool
Whether the profile was created or reopened through this API.
copy_report
ChromiumProfileCopyReport | None
Optional report describing data copied into a generated profile.
Nonemeans no copy report is available.Examples
Describe an existing profile location without opening Chromium:
from pathlib import Path from ddp_utils.browser.profile import ChromiumProfile profile = ChromiumProfile( browser="chrome", user_data_dir=Path("profiles/chrome"), profile_directory="Default", )
- property profile_path: Path¶
Return the concrete profile directory inside the user-data root.
Returns
The absolute user-data root when
profile_directoryis.; otherwise that root joined with the configured subdirectory name.Examples
Resolve the selected profile directory:
path = profile.profile_path
- property is_system_default: bool¶
Return whether this object points at the product’s standard data root.
Returns
Truewhenuser_data_direquals the platform-specific default for the configured browser; otherwiseFalse.Examples
Check whether profile data uses the browser’s default root:
uses_default_root = profile.is_system_default
- ensure_closed() None¶
Fail conservatively when the selected browser profile may be in use.
Raises
Exception
Description
If the browser appears to be running with this profile.
Examples
Use this public operation:
result = chromium_profile.ensure_closed()
- classmethod default(browser: str, *, profile_directory: str | None = None) ChromiumProfile¶
Describe the browser’s platform-default user-data directory.
This operation computes paths only; it does not create directories or start a browser process.
Parameters
Name
Type
Description
browser
str
Supported Chromium product name or recognized Chrome or Edge alias.
profile_directory
str | None
Profile subdirectory name.
Noneselects the product’s default profile directory.Returns
Type
Description
A normalized profile descriptor for the current platform.
Raises
Exception
Description
ValueError
browseris empty orprofile_directoryis not one directory name.KeyError
The normalized browser product is unsupported.
Examples
Describe Chrome’s standard default profile:
from ddp_utils.browser.profile import ChromiumProfile profile = ChromiumProfile.default("chrome")
- classmethod minimal(browser: str, destination: Path | str, *, profile_directory: str | None = None, source: ChromiumProfile | None = None, copy: ChromiumProfileCopyOptions | None = None, unpacked_extensions: Sequence[Path | str] = ()) ChromiumProfile¶
Create a new minimal profile and optionally seed selected data.
The destination must be absent or empty. Existing files are never overwritten. The source browser profile must be completely closed. Data is assembled in a temporary staging directory and then moved into the destination; filesystem failures may therefore leave a partially moved destination, but existing destination content is never deleted.
Parameters
Name
Type
Description
browser
str
Supported Chromium product name or recognized alias.
destination
Path | str
New or empty user-data directory to populate.
profile_directory
str | None
Destination profile subdirectory.
Noneuses the product default.source
ChromiumProfile | None
Optional closed source profile.
Noneselects the system default profile only whencopyrequests source data.copy
ChromiumProfileCopyOptions | None
Optional data-selection policy.
Noneuses the default policy, which creates an empty minimal profile.unpacked_extensions
Sequence[Path | str]
Additional unpacked-extension directories to validate and associate with the result.
Returns
Type
Description
A generated profile descriptor whose
copy_reportrecords copied, missing, and warned-about entries and discovered extensions.Raises
Exception
Description
Source and destination browsers differ, the source is missing or may be open, the destination lies inside the source, or the destination is not an empty directory.
ValueError
A browser or profile-directory value is invalid.
FileNotFoundError
A requested unpacked extension or selected source entry does not exist.
OSError
Directory creation, copying, validation, or the final move fails.
Examples
Create an empty disposable Chrome profile:
from pathlib import Path from tempfile import TemporaryDirectory from ddp_utils.browser.profile import ChromiumProfile with TemporaryDirectory() as directory: profile = ChromiumProfile.minimal( "chrome", Path(directory, "profile"), ) assert profile.generated
- classmethod existing(browser: str, user_data_dir: Path | str, *, profile_directory: str | None = None) ChromiumProfile¶
Open a generated profile and rediscover its copied unpacked extensions.
This operation validates the root and inspects its
Unpacked Extensionsdirectory. It does not start Chromium or verify that the profile is closed.Parameters
Name
Type
Description
browser
str
Supported Chromium product name or recognized alias.
user_data_dir
Path | str
Existing user-data root to describe.
profile_directory
str | None
Profile subdirectory name.
Noneuses the product default.Returns
Type
Description
A generated profile descriptor containing each valid unpacked extension discovered below the user-data root.
Raises
Exception
Description
user_data_diris not an existing directory.ValueError
The browser is empty or the profile directory is invalid.
Examples
Reopen a previously generated profile:
from tempfile import TemporaryDirectory from ddp_utils.browser.profile import ChromiumProfile with TemporaryDirectory() as directory: profile = ChromiumProfile.existing("chrome", directory) assert profile.generated
- class ddp_utils.browser.cdp.ChromiumWarmupResult(requested_url: str, final_url: str, title: str)¶
Bases:
objectDescribe one browser-managed navigation used to initialize a profile.
Examples
Use this public operation:
instance = ChromiumWarmupResult()
- class ddp_utils.browser.cdp.LocalChromiumBrowser(browser: str = 'chrome', *, executable_path: Path | str | None = None, user_data_dir: Path | str | None = None, profile: ChromiumProfile | None = None, headless: bool = False, startup_timeout: float = 20.0, arguments: Sequence[str] = (), extensions: Sequence[Path | str] = ())¶
Bases:
objectLaunch an installed Chromium browser and control it without WebDriver.
The class owns only the browser process, its optional temporary profile, and a loopback CDP connection. Scenario-specific HTTP servers, extensions, and JavaScript APIs are supplied by callers.
Examples
Use this public operation:
instance = LocalChromiumBrowser()
Configure a local Chromium process without starting it.
Parameters
Name
Type
Description
browser
str
Chromium browser name, for example
"chrome".executable_path
Optional[Path | str]
Explicit browser executable path.
user_data_dir
Optional[Path | str]
Browser profile directory; mutually exclusive with
profile.profile
Optional[ChromiumProfile]
Configured
ChromiumProfile: its directory and unpacked extensions are used; its browser must matchbrowser.headless
bool
Run the browser without a visible window.
startup_timeout
float
Seconds to wait for the CDP endpoint at startup; must be greater than zero.
arguments
Sequence[str]
Extra command-line arguments for the browser process.
extensions
Sequence[Path | str]
Unpacked extension directories to load, added to those of
profile.Raises
Exception
Description
ValueError
If
browseris not a Chromium browser,startup_timeoutis not greater than zero, bothprofileanduser_data_dirare given, or the profile belongs to a different browser.- classmethod installed(browsers: Sequence[str] = ('chrome', 'edge', 'brave', 'chromium', 'opera')) list[ChromiumInstallation]¶
Return detected compatible browser installations.
Parameters
Name
Type
Description
browsers
Sequence[str]
Chromium product names to inspect in order. Supported names are
chrome,edge,brave,chromium, andopera; common Chrome and Edge aliases are normalized.Returns
Type
Description
list[ChromiumInstallation]
Detected installations in request order, with duplicate executable paths removed. An empty list means none were found.
Raises
Exception
Description
KeyError
A requested browser name is not supported.
Examples
Discover installed Chrome-family browsers:
from ddp_utils.browser.cdp import LocalChromiumBrowser installations = LocalChromiumBrowser.installed(("chrome", "edge"))
- classmethod attach(port: int, *, host: str = '127.0.0.1', page_url: str | None = None, timeout: float = 10.0) LocalChromiumBrowser¶
Attach to an already running local Chromium CDP page target.
The returned instance owns the websocket connection but never terminates the externally managed browser process.
Parameters
Name
Type
Description
port
int
Remote-debugging TCP port in the inclusive range 1 through 65535.
host
str
Loopback host. Only
127.0.0.1,localhost, and::1are accepted.page_url
str | None
Optional URL prefix used to select a page target.
Noneaccepts the first stable page target.timeout
float
Positive number of seconds allowed for target discovery and websocket connection.
Returns
Type
Description
A browser controller attached to the selected page. Call
close()to release its websocket connection.Raises
Exception
Description
ValueError
The host is not loopback, or the port or timeout is not valid.
RuntimeError
The optional websocket dependency is unavailable.
Chromium does not expose a matching page before timeout.
OSError
The local debugging endpoint or websocket cannot be opened.
Examples
Attach to Chromium started with remote debugging enabled:
from ddp_utils.browser.cdp import LocalChromiumBrowser browser = LocalChromiumBrowser.attach(9222) try: title = browser.evaluate("document.title") finally: browser.close()
- start(url: str = 'about:blank') LocalChromiumBrowser¶
Launch the configured browser and attach to its initial page target.
Starting an already connected instance is idempotent. A new launch may create a temporary profile, starts a local process with a loopback CDP port, and removes owned resources if attachment fails.
Parameters
Name
Type
Description
url
str
Initial URL passed to Chromium and used to select its first page target.
Returns
Type
Description
This browser controller after the CDP connection is ready.
Raises
Exception
Description
FileNotFoundError
The browser executable or an extension manifest cannot be found.
RuntimeError
The optional websocket dependency is unavailable.
The selected profile is incompatible or busy, or Chromium does not expose the requested page before timeout.
OSError
Profile creation, process launch, or websocket connection fails.
Examples
Start and reliably close a headless local browser:
from ddp_utils.browser.cdp import LocalChromiumBrowser browser = LocalChromiumBrowser(headless=True) try: browser.start("https://example.com") finally: browser.close()
- command(method: str, params: Mapping[str, Any] | None = None) Mapping[str, Any]¶
Execute a CDP command on the attached page target.
Parameters
Name
Type
Description
method
str
Fully qualified CDP method name.
params
Mapping[str, Any] | None
Optional JSON-serializable command parameters.
Nonesends an empty mapping.Returns
Type
Description
Mapping[str, Any]
A new dictionary containing the command’s result object.
Raises
Exception
Description
RuntimeError
This browser has not been started or attached.
Chromium rejects the command, the connection closes, or the response is invalid.
Examples
Query browser metadata from a running controller:
version = browser.command("Browser.getVersion")
- evaluate(expression: str, *, await_promise: bool = False) Any¶
Evaluate JavaScript on the attached page target.
Parameters
Name
Type
Description
expression
str
JavaScript source evaluated in the current page.
await_promise
bool
Wait for a returned promise to settle when
True.Returns
Type
Description
Any
The JSON-compatible value copied from Chromium, or
Nonewhen the expression has no serializable result.Raises
Exception
Description
RuntimeError
This browser has not been started or attached.
The protocol command or evaluated JavaScript fails.
Examples
Read a value from the current document:
title = browser.evaluate("document.title")
Navigate the attached target and wait for its load event.
Parameters
Name
Type
Description
url
str
Destination passed unchanged to
Page.navigate.Raises
Exception
Description
RuntimeError
This browser has not been started or attached.
Navigation, load waiting, or the underlying connection fails.
Examples
Navigate an already running controller:
browser.navigate("https://example.com")
- warm_up(urls: Sequence[str], *, dwell_time: float = 0.5) tuple[ChromiumWarmupResult, ...]¶
Initialize a persistent profile through ordinary HTTP(S) navigation.
Chromium itself creates history, cache, cookies, storage, and preference files. The method does not fabricate or edit Chromium databases.
Parameters
Name
Type
Description
urls
Sequence[str]
Nonempty sequence of HTTP or HTTPS URLs visited in order.
dwell_time
float
Nonnegative delay in seconds between consecutive URLs.
Returns
Type
Description
tuple[ChromiumWarmupResult, …]
One immutable result per requested URL, preserving input order and recording the final page URL and title observed after navigation.
Raises
Exception
Description
RuntimeError
This browser has not been started or attached.
ValueError
No URLs are supplied, a URL is not HTTP(S), or
dwell_timeis negative.Navigation or page evaluation fails.
Examples
Visit pages while building a persistent browser profile:
results = browser.warm_up( ("https://example.com", "https://www.iana.org/"), dwell_time=0.25, )
- close() None¶
Close CDP, terminate the owned browser, and remove its temporary profile.
Examples
Use this public operation:
result = local_chromium_browser.close()