ScreenshotNeo

BlogHow-to

How to Use Chrome DevTools with Selenium 4

Use Selenium 4 to send Chrome DevTools Protocol commands, understand the version limits, and choose WebDriver BiDi for browser events.

By the ScreenshotNeo team4 October 20268 min read

To use Chrome DevTools with Selenium 4, send commands through the Chrome DevTools Protocol (CDP) API exposed by your Selenium language binding. In Python, call driver.execute_cdp_cmd(command, arguments); in Java, cast the driver to HasCdp and call executeCdpCommand. These calls use a command name and a map of protocol arguments, then return a response. For continuous console or network events, consider Selenium WebDriver BiDi instead: it provides a bidirectional, standards-based interface.

Here, “Chrome DevTools” means programmatic access to CDP. Selenium does not use WebDriver to open the interactive DevTools panel and operate it. See Selenium’s CDP documentation and the ScreenshotNeo API documentation for the separate screenshot workflow later in this guide.

1. Choose CDP or WebDriver BiDi

Need Use Reason
Send one browser command and read its response, such as setting a cookie CDP command API The documented API is command/response.
Subscribe to console logs or network events WebDriver BiDi where supported by your binding and browser BiDi exposes bidirectional event features over a WebSocket.
Cross-browser automation or a standards-based interface Evaluate WebDriver BiDi Selenium describes BiDi as its W3C standards-based, cross-browser direction.

CDP is version-sensitive. Selenium cautions that it is not designed as a stable testing API and that functionality depends heavily on browser version. The Selenium documentation describes support for the three most recent Chrome versions at a given time; this window moves. Check the current compatibility guidance and your language binding’s reference before relying on a command.

2. Python: send a CDP command

The Python WebDriver API documents execute_cdp_cmd(cmd, cmd_args). This runnable example starts Chrome, sets a cookie for the current origin, reads it back through WebDriver, and closes the browser even if a step fails. Install Selenium with python -m pip install selenium and make Chrome available to Selenium’s driver management or configure the driver for your environment.

from selenium import webdriver

options = webdriver.ChromeOptions()
# For a headless run, uncomment:
# options.add_argument("--headless=new")

driver = webdriver.Chrome(options=options)
try:
    driver.get("https://example.com")

    response = driver.execute_cdp_cmd(
        "Network.setCookie",
        {
            "name": "session_hint",
            "value": "selenium-cdp",
            "url": "https://example.com/",
            "sameSite": "Lax",
            "secure": True,
        },
    )
    print("CDP response:", response)

    # Verify through the WebDriver cookie API.
    print("Cookies:", driver.get_cookies())
finally:
    driver.quit()

The command uses the Network domain and the setCookie command. Its arguments must match the protocol schema for the Chrome version in use. A CDP command does not automatically become a portable WebDriver feature, and not every command is available through every binding or browser version. The Python method returns the command’s JSON response; consult the Selenium Python API reference for its current signature.

3. Java: send a CDP command

Selenium’s Java example uses the HasCdp interface. With Selenium Java and a configured ChromeDriver on the classpath, the core pattern is:

import java.util.HashMap;
import java.util.Map;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chromium.HasCdp;

public class CdpCookieExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");

            Map<String, Object> cookie = new HashMap<>();
            cookie.put("name", "session_hint");
            cookie.put("value", "selenium-cdp");
            cookie.put("url", "https://example.com/");
            cookie.put("sameSite", "Lax");
            cookie.put("secure", true);

            Map<String, Object> argsMap = new HashMap<>();
            argsMap.put("cookie", cookie);

            Object response = ((HasCdp) driver).executeCdpCommand(
                "Network.setCookie", argsMap);
            System.out.println("CDP response: " + response);
        } finally {
            driver.quit();
        }
    }
}

Use the exact command and parameter names documented for the protocol domain. Selenium’s example demonstrates Network.setCookie; it does not mean every protocol command works in every Selenium release. Check the Selenium CDP page and the reference for your binding rather than copying method names across languages.

4. Understanding commands, domains, and responses

A CDP command has a domain-qualified name and an argument object. The domain groups related browser operations: for example, Network.setCookie belongs to Network. To use a different command:

  1. Find the protocol domain and command that match the operation.
  2. Read the command’s required and optional parameters, including types and valid values.
  3. Pass the domain-qualified command name and a language-appropriate map or dictionary of arguments.
  4. Inspect the returned response and handle protocol errors in your application.
  5. Keep the command covered by a small compatibility check when upgrading Selenium or Chrome.

Some protocol tasks require enabling a domain before using its commands or events. Follow the command’s protocol documentation and Selenium binding API; do not assume that a command shown in one language has an identical wrapper in another. Selenium’s CDP guide specifically calls out the need to know domains, command names, parameter names, and types.

5. When you need browser events: WebDriver BiDi

A one-shot CDP command is different from listening for events. If the task is to collect console messages as they occur or react to network requests, use Selenium’s WebDriver BiDi features where they are implemented for your browser and language. Selenium documents logging handlers and network request handlers, and its BiDi setup uses a WebSocket connection in browser options.

For example, Selenium’s Python logging guide shows an event-driven pattern along these lines (the exact API can evolve, so follow the current guide for imports and setup):

from selenium import webdriver
from selenium.webdriver.common.bidi.console import Console

options = webdriver.ChromeOptions()
options.enable_bidi = True

driver = webdriver.Chrome(options=options)
try:
    # BiDi event APIs are asynchronous; use the current Selenium Python
    # logging guide for its supported event-loop and handler setup.
    driver.get("https://example.com")
finally:
    driver.quit()

The snippet enables the BiDi connection; event subscription and callback syntax depend on the binding version. See Selenium’s WebDriver BiDi overview, logging guide, and Python BiDi network API. Selenium notes that implementation and browser support continue to grow, so check current support before adopting a feature.

6. Version compatibility and maintenance

  • Pin or control your browser and Selenium versions: CDP protocol details can change with Chrome.
  • Check the moving support window: Selenium documents support for the three most recent Chrome versions at a given time. That is a policy description, not a permanent list of version numbers.
  • Read release-specific notes: Selenium 4.40’s January 18, 2026 announcement listed DevTools versions 144, 143, and 142 for that release. This is historical release context, not a current compatibility guarantee.
  • Revisit CDP calls on upgrades: verify command schemas and response handling when the browser or Selenium changes.
  • Prefer BiDi for new event-driven, cross-browser requirements: verify feature support in the specific browser and binding first.

Because CDP is version-dependent, treat it as an integration boundary: keep protocol-specific code in a small helper, surface useful errors, and run your project’s existing compatibility checks against the browser versions you support.

7. Troubleshooting

Symptom Likely cause What to do
execute_cdp_cmd or executeCdpCommand is missing The binding, driver type, or Selenium version does not expose the method you are calling. Check the current API reference for that language. In Java, Selenium’s documented pattern uses HasCdp; Python has its own method signature.
Unknown command or protocol error The command name is wrong, the domain is unavailable, or the browser’s protocol version differs from expectations. Check spelling, domain, browser version, Selenium support window, and the command’s required parameters.
Invalid parameters or unexpected response A parameter has the wrong name, type, or value, or the response differs across protocol versions. Compare your argument map with the protocol schema for the active browser and validate the returned JSON before using it.
Cookie does not appear The cookie URL or domain does not match the page, or cookie attributes conflict with the context. Navigate to the intended origin first; check URL/domain, secure context, same-site setting, and the command response. Verify using WebDriver’s cookie API.
Events never arrive A command/response call is being used for an event-streaming task, or BiDi is not enabled/supported. Use the binding’s BiDi event API, enable the BiDi connection as documented, and confirm browser support and handler setup.
Works locally but fails after browser update CDP is version-sensitive and protocol behavior can change. Check Selenium’s current compatibility notes and release information, then update the command integration for the new browser protocol.

8. Performance, reliability, and cost

A CDP command adds a browser-driver round trip, so avoid issuing unnecessary commands inside tight loops. Batch work at the application level where the protocol command permits it, and prefer WebDriver’s standard API when it already covers the task. No benchmark or fixed latency is implied: actual time depends on browser work, the driver connection, and the command.

For reliability, always close the driver in a finally block, validate command responses, and test the Chrome/Selenium combinations your application supports. CDP can be useful for capabilities not directly exposed by WebDriver, but its version sensitivity creates maintenance work. WebDriver BiDi is the standards-based route Selenium describes for bidirectional and cross-browser use cases, subject to implementation support.

Selenium and CDP are software interfaces; the dossier provides no pricing figures for them. Operational cost depends on the machines and infrastructure running browser sessions. For screenshot-only jobs, a screenshot API can avoid maintaining your own browser setup; see the option below.

9. Or skip the browser setup

If your goal is a page screenshot rather than inspecting browser internals, ScreenshotNeo offers a single GET request that returns an image or PDF. This is separate from Selenium/CDP: use Selenium when you need browser automation or protocol access, and use a screenshot API when you need the rendered page artifact.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Equivalent Python and Node.js calls are available. The API supports PNG, JPEG, WebP, or PDF output and the ScreenshotNeo documentation lists request options.

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

10. FAQ

Can Selenium click the DevTools panel?

This guide covers sending protocol commands through Selenium, not automating the interactive DevTools interface. Use WebDriver to interact with the page, and CDP or BiDi APIs for their supported browser capabilities.

Does every Selenium 4 language use the same method?

No. The method and available APIs depend on the language binding. Use that binding’s current Selenium reference.

Should I use CDP for a new cross-browser feature?

Consider WebDriver BiDi because Selenium positions it as its standards-based, cross-browser alternative. Confirm that the specific feature is implemented in your target browser and binding.

Where can I find the current Chrome CDP version support?

Use Selenium’s current CDP documentation and release notes. Version examples in dated release announcements describe those releases only.

Sources