ddp_utils.browser.network.capture¶
import ddp_utils.browser.network.capture
Native network capture and interception for Selenium browser sessions.
Chromium browsers use Selenium’s typed DevTools websocket API. Firefox and
other WebDriver BiDi implementations use BiDi network events plus a preload
script that captures response bodies for page-level XHR and fetch calls.
No MITM proxy and no Selenium Wire dependency is used.
- class ddp_utils.browser.network.capture.BidiNetworkCapture(driver: Any, settings: NetworkCaptureSettings)¶
Bases:
NetworkCaptureCapture browser-neutral network metadata through WebDriver BiDi.
Examples
Use this public operation:
instance = BidiNetworkCapture(driver, settings)
Initialize BiDi and JavaScript fallback state.
Parameters
Name
Type
Description
driver
Any
WebDriver created with
webSocketUrlcapability.settings
Capture settings.
- start() BidiNetworkCapture¶
Subscribe to BiDi network events and install body instrumentation.
Returns
Type
Description
This adapter.
Raises
Exception
Description
If WebDriver BiDi is unavailable.
Examples
Use this public operation:
result = bidi_network_capture.start()
- poll() int¶
Merge page-level XHR/fetch bodies into BiDi metadata.
Returns
Type
Description
int
Number of JavaScript entries processed.
Examples
Use this public operation:
result = bidi_network_capture.poll()
- close() None¶
Unsubscribe BiDi callbacks and remove the preload script.
Examples
Use this public operation:
result = bidi_network_capture.close()
- class ddp_utils.browser.network.capture.ChromiumNetworkCapture(driver: Any, settings: NetworkCaptureSettings)¶
Bases:
NetworkCaptureCapture and intercept Chromium traffic through Selenium DevTools.
Examples
Use this public operation:
instance = ChromiumNetworkCapture(driver, settings)
Initialize protocol state without opening a websocket yet.
Parameters
Name
Type
Description
driver
Any
Chromium WebDriver exposing
start_devtools.settings
Capture settings.
- start() ChromiumNetworkCapture¶
Start typed CDP subscriptions and body retrieval.
Returns
Type
Description
This adapter.
Raises
Exception
Description
If Selenium cannot start DevTools.
Examples
Use this public operation:
result = chromium_network_capture.start()
- enable_interception(url_patterns: Sequence[str] = ('*',)) None¶
Enable Chromium Fetch interception for blocking, headers, and mocks.
Parameters
Name
Type
Description
url_patterns
Sequence[str]
CDP Fetch URL patterns.
Raises
Exception
Description
If Fetch interception cannot be enabled.
Examples
Use this public operation:
result = chromium_network_capture.enable_interception()
- disable_interception() None¶
Disable Chromium Fetch interception and clear all rules.
Examples
Use this public operation:
result = chromium_network_capture.disable_interception()
- block_urls(substrings: Iterable[str]) None¶
Add URL fragments blocked by CDP Fetch.
Parameters
Name
Type
Description
substrings
Iterable[str]
Case-sensitive URL fragments.
Examples
Use this public operation:
result = chromium_network_capture.block_urls(substrings)
- set_extra_headers(headers: Mapping[str, str]) None¶
Replace headers merged into intercepted Chromium requests.
Parameters
Name
Type
Description
headers
Mapping[str, str]
Header names and values.
Examples
Use this public operation:
result = chromium_network_capture.set_extra_headers(headers)
- mock_response(url_contains: str, response: MockResponse) None¶
Register a Chromium Fetch mock response.
Parameters
Name
Type
Description
url_contains
str
URL fragment to match.
response
Synthetic response.
Raises
Exception
Description
ValueError
If the URL fragment is empty.
Examples
Use this public operation:
result = chromium_network_capture.mock_response(url_contains, response)
- close() None¶
Disable CDP domains and detach every callback.
Examples
Use this public operation:
result = chromium_network_capture.close()
- class ddp_utils.browser.network.capture.JavaScriptNetworkCapture(driver: Any, settings: NetworkCaptureSettings)¶
Bases:
BidiNetworkCaptureCapture page-level XHR/fetch calls when neither CDP nor BiDi exists.
Examples
Use this public operation:
instance = JavaScriptNetworkCapture()
Initialize BiDi and JavaScript fallback state.
Parameters
Name
Type
Description
driver
Any
WebDriver created with
webSocketUrlcapability.settings
Capture settings.
- start() JavaScriptNetworkCapture¶
Inject capture into the current document.
Returns
Type
Description
This adapter.
Raises
Exception
Description
If the JavaScript capture cannot be injected into the page.
Examples
Use this public operation:
result = java_script_network_capture.start()
- close() None¶
Stop polling; page instrumentation expires with its document.
Examples
Use this public operation:
result = java_script_network_capture.close()
- class ddp_utils.browser.network.capture.MockResponse(status: int = 200, headers: Mapping[str, str]=<factory>, body: str | bytes = '', reason: str | None = None)¶
Bases:
objectDescribe a synthetic response returned by Chromium interception.
Parameters
Name
Type
Description
status
int
HTTP status code.
headers
Mapping[str, str]
Response headers.
body
str | bytes
UTF-8 text or raw bytes.
reason
str | None
Optional HTTP reason phrase.
Examples
Use this public operation:
instance = MockResponse()
- class ddp_utils.browser.network.capture.NetworkCapture(driver: Any, settings: NetworkCaptureSettings)¶
Bases:
objectBackend-neutral interface implemented by native capture adapters.
Examples
Use this public operation:
instance = NetworkCapture(driver, settings)
Store the WebDriver and capture settings.
Parameters
Name
Type
Description
driver
Any
Active Selenium WebDriver.
settings
Validated capture settings.
- property active: bool¶
Return whether the capture adapter is subscribed.
Returns
Current subscription state.
Falsealso covers an adapter that has not been started or has already been closed.Examples
Check state before collecting records:
if not capture.active: capture.start()
- start() NetworkCapture¶
Start collecting network events.
Returns
Type
Description
The same capture object for fluent setup.
Examples
Use this public operation:
result = network_capture.start()
- poll() int¶
Process pending data for polling-based fallback adapters.
Returns
Type
Description
int
Number of new or updated records.
Examples
Use this public operation:
result = network_capture.poll()
- records(capture_filter: NetworkFilter | None = None, *, refresh: bool = True) list[NetworkRecord]¶
Return a stable snapshot of captured records.
Parameters
Name
Type
Description
capture_filter
NetworkFilter | None
Optional query filter.
refresh
bool
Call
poll()before creating the snapshot.Returns
Type
Description
list[NetworkRecord]
Ordered records that match the active filter.
Examples
Use this public operation:
result = network_capture.records()
- json_responses(url_contains: str | None = None) list[tuple[str, Any]]¶
Return successfully parsed JSON response bodies.
Parameters
Name
Type
Description
url_contains
str | None
Optional case-insensitive URL substring.
Returns
Type
Description
list[tuple[str, Any]]
(url, decoded_json)tuples for valid JSON bodies.Examples
Use this public operation:
result = network_capture.json_responses()
- wait_for(capture_filter: NetworkFilter, *, timeout: float = 10.0, interval: float = 0.05, require_complete: bool = True) NetworkRecord¶
Wait until a captured request matches a filter.
Parameters
Name
Type
Description
capture_filter
Predicates for the desired record.
timeout
float
Maximum wait in seconds.
interval
float
Polling interval in seconds.
require_complete
bool
Require response completion or terminal failure.
Returns
Type
Description
The first matching record.
Raises
Exception
Description
TimeoutError
If no matching record arrives before the deadline.
Examples
Use this public operation:
result = network_capture.wait_for(capture_filter)
- clear() None¶
Discard all retained records without stopping capture.
Examples
Use this public operation:
result = network_capture.clear()
- enable_interception(url_patterns: Sequence[str] = ('*',)) None¶
Enable request interception when supported by the adapter.
Parameters
Name
Type
Description
url_patterns
Sequence[str]
Protocol URL patterns to intercept.
Raises
Exception
Description
NotImplementedError
If the selected protocol cannot intercept.
Examples
Use this public operation:
result = network_capture.enable_interception()
- disable_interception() None¶
Disable request interception and remove all active rules.
Raises
Exception
Description
NotImplementedError
Always in this base class: request interception is unavailable.
Examples
Use this public operation:
result = network_capture.disable_interception()
- block_urls(substrings: Iterable[str]) None¶
Block requests whose URL contains any supplied substring.
Parameters
Name
Type
Description
substrings
Iterable[str]
Case-sensitive URL fragments.
Raises
Exception
Description
NotImplementedError
If interception is unavailable.
Examples
Use this public operation:
result = network_capture.block_urls(substrings)
- set_extra_headers(headers: Mapping[str, str]) None¶
Set headers merged into every intercepted request.
Parameters
Name
Type
Description
headers
Mapping[str, str]
Request header values.
Raises
Exception
Description
NotImplementedError
If interception is unavailable.
Examples
Use this public operation:
result = network_capture.set_extra_headers(headers)
- mock_response(url_contains: str, response: MockResponse) None¶
Return a synthetic response for matching requests.
Parameters
Name
Type
Description
url_contains
str
URL substring identifying requests to mock.
response
Synthetic response definition.
Raises
Exception
Description
NotImplementedError
If response fulfillment is unavailable.
Examples
Use this public operation:
result = network_capture.mock_response(url_contains, response)
- close() None¶
Stop capture and release adapter-owned listeners.
Examples
Use this public operation:
result = network_capture.close()
- exception ddp_utils.browser.network.capture.NetworkCaptureError¶
Bases:
RuntimeErrorBase error raised by the native network capture service.
Examples
Use this public operation:
instance = NetworkCaptureError()
- class ddp_utils.browser.network.capture.NetworkCaptureMode(value)¶
Bases:
str,EnumSelect the native protocol used for network events.
Examples
Use this public operation:
instance = NetworkCaptureMode()
- classmethod parse(value: Any) NetworkCaptureMode¶
Normalize a user-provided capture mode.
Parameters
Name
Type
Description
value
Any
Existing enum value or case-insensitive string.
Returns
Type
Description
A normalized
NetworkCaptureMode.Raises
Exception
Description
ValueError
If the mode is unknown.
Examples
Use this public operation:
result = network_capture_mode.parse(value)
- class ddp_utils.browser.network.capture.NetworkCaptureSettings(enabled: bool = False, mode: NetworkCaptureMode = NetworkCaptureMode.AUTO, auto_start: bool = True, capture_bodies: bool = True, javascript_bodies: bool = True, max_body_bytes: int = 5242880, buffer_size: int = 10000, required: bool = True, default_filter: NetworkFilter = <factory>)¶
Bases:
objectConfigure session-owned native network capture.
Parameters
Name
Type
Description
enabled
bool
Create a capture service for the browser session.
mode
autoselects CDP for Chromium and BiDi elsewhere.auto_start
bool
Start capture before navigating to
start_url.capture_bodies
bool
Retrieve response bodies when the protocol supports it.
javascript_bodies
bool
Add page-level XHR/fetch body capture to BiDi mode.
max_body_bytes
int
Maximum retained body size per response.
buffer_size
int
Maximum number of records retained in memory.
required
bool
Fail browser startup when capture cannot be initialized.
default_filter
Filter applied by
records()when none is supplied.Examples
Use this public operation:
instance = NetworkCaptureSettings()
- class ddp_utils.browser.network.capture.NetworkFilter(url_contains: str | None = None, methods: tuple[str, ...] = (), statuses: tuple[int, ...] = (), resource_types: tuple[str, ...] = ())¶
Bases:
objectFilter captured records without affecting browser traffic.
Parameters
Name
Type
Description
url_contains
str | None
Case-insensitive URL substring.
methods
tuple[str, ...]
Allowed HTTP methods.
statuses
tuple[int, ...]
Allowed HTTP response statuses.
resource_types
tuple[str, ...]
Allowed protocol resource types such as
xhr.Examples
Use this public operation:
instance = NetworkFilter()
- matches(record: NetworkRecord) bool¶
Return whether a record satisfies all configured predicates.
Parameters
Name
Type
Description
record
Captured network record.
Returns
Type
Description
bool
Truewhen every active predicate matches.Examples
Use this public operation:
result = network_filter.matches(record)
- class ddp_utils.browser.network.capture.NetworkRecord(request_id: str, url: str, method: str = 'GET', resource_type: str = 'other', request_headers: dict[str, ~typing.Any]=<factory>, request_body: str | None = None, status: int | None = None, status_text: str | None = None, response_headers: dict[str, ~typing.Any]=<factory>, mime_type: str | None = None, response_body: str | None = None, response_body_is_base64: bool = False, encoded_data_length: float | None = None, error: str | None = None, started_at: float | None = None, completed_at: float | None = None, source: str = 'unknown')¶
Bases:
objectRepresent one browser request and its optional response.
Parameters
Name
Type
Description
request_id
str
Protocol request identifier.
url
str
Absolute request URL.
method
str
HTTP method.
resource_type
str
Protocol resource classification.
request_headers
dict[str, Any]
Request headers.
request_body
str | None
Request payload when available.
status
int | None
HTTP response status.
status_text
str | None
HTTP response reason phrase.
response_headers
dict[str, Any]
Response headers.
mime_type
str | None
Response media type.
response_body
str | None
Text or base64 body returned by the protocol.
response_body_is_base64
bool
Whether
response_bodyis base64 encoded.encoded_data_length
float | None
Encoded transfer size.
error
str | None
Protocol loading error.
started_at
float | None
Protocol or wall-clock request timestamp.
completed_at
float | None
Wall-clock completion timestamp.
source
str
cdp,bidi, orjavascript.Examples
Represent one pending request:
record = NetworkRecord("request-1", "https://example.com/")
- property complete: bool¶
Return whether the request has a response or terminal error.
Returns
Truewhencompleted_atorerroris set; otherwiseFalsefor a still-pending request.Examples
Distinguish pending and terminal records:
assert record.complete is False
- body_bytes() bytes | None¶
Decode the response body to bytes.
Returns
Type
Description
bytes | None
Raw response bytes, or
Noneif no body was captured.Examples
Use this public operation:
result = network_record.body_bytes()
- json_body() Any¶
Parse the response body as JSON.
Returns
Type
Description
Any
The decoded JSON value.
Raises
Exception
Description
ValueError
If no body was captured.
json.JSONDecodeError
If the body is not valid JSON.
Examples
Use this public operation:
result = network_record.json_body()
- to_dict() dict[str, Any]¶
Return a detached dictionary representation of the record.
Returns
Type
Description
dict[str, Any]
A recursively copied mapping of every dataclass field. Mutating the returned header mappings does not change this record.
Examples
Serialize a record for logging or JSON encoding:
payload = record.to_dict() assert payload["request_id"] == "request-1"
- class ddp_utils.browser.network.capture.PlaywrightNetworkCapture(driver: Any, settings: NetworkCaptureSettings)¶
Bases:
NetworkCaptureCapture complete page traffic through Playwright-compatible events.
Examples
Use this public operation:
instance = PlaywrightNetworkCapture(driver, settings)
Bind the native page without registering listeners yet.
Parameters
Name
Type
Description
driver
Any
PlaywrightDriverAdapter or Camoufox-compatible adapter.
settings
Bounded network capture settings.
Examples
capture = PlaywrightNetworkCapture(driver, settings)
- start() PlaywrightNetworkCapture¶
Subscribe to native request lifecycle events.
Returns
Type
Description
This active capture instance.
Raises
Exception
Description
The adapter exposes no compatible native page.
Examples
capture.start()
- close() None¶
Detach every native event callback and close the capture.
Examples
Use this public operation:
result = playwright_network_capture.close()
- ddp_utils.browser.network.capture.create_network_capture(driver: Any, browser: str, settings: NetworkCaptureSettings) NetworkCapture¶
Create the native capture adapter required by a browser.
Parameters
Name
Type
Description
driver
Any
Active WebDriver.
browser
str
Canonical browser name.
settings
Capture settings.
Returns
Type
Description
Unstarted capture adapter.
Raises
Exception
Description
If an explicitly requested mode is unsupported.
Examples
Use this public operation:
result = create_network_capture(driver, browser, settings)