sodcalculator

10 Tech How-To

Chrome DevTools with Selenium: A How-To Guide

Guide 10-49745 · Updated · Step by step

This guide shows you how to use Chrome DevTools Protocol (CDP) features from your Selenium tests, letting you emulate device metrics, capture network performance, and intercept browser requests. You’ll learn to set up a Selenium script that connects to Chrome’s DevTools and executes commands that go beyond the standard WebDriver API.

What You’ll Need

  • Python 3.7+ installed (the examples use Python, but the concepts apply to Java, C#, and Ruby as well)
  • Selenium WebDriver installed: pip install selenium
  • Chrome browser (current version) and ChromeDriver that matches your Chrome version
  • Basic understanding of Selenium WebDriver (finding elements, clicks, waits)

Step-by-Step

  1. Set up your Selenium project. Create a new Python file (e.g., devtools_demo.py) and import the required modules: from selenium import webdriver and from selenium.webdriver.chrome.options import Options.
  2. Enable DevTools support. When creating the Chrome driver, add the --remote-debugging-port argument (e.g., port 9222) so Selenium can talk to Chrome’s DevTools. Alternatively, in Selenium 4+, you can use the built-in driver.execute_cdp_cmd() method without a separate port—this is the easiest path.
  3. Start a Chrome session. Example: driver = webdriver.Chrome(). This automatically launches Chrome with a fresh profile.
  4. Use execute_cdp_cmd for CDP commands. This method takes two arguments: the CDP command name (a string) and a dictionary of parameters. For instance, to emulate a mobile device, call driver.execute_cdp_cmd("Emulation.setDeviceMetricsOverride", {"width": 375, "height": 812, "deviceScaleFactor": 3, "mobile": True}).
  5. Navigate to a page. Use driver.get("https://example.com") after setting up any CDP overrides, so the page renders with those settings.
  6. Capture network activity. Enable the Network domain by calling driver.execute_cdp_cmd("Network.enable", {}). Then, after the page loads, retrieve performance logs via driver.get_log("performance") to see network requests, timings, and responses.
  7. Intercept requests (optional). Use Network.setRequestInterception with a pattern to block or modify requests. You’ll need to handle the interception events in a listener—this is more advanced and often requires a separate thread or a custom event loop.
  8. Take a screenshot with device metrics. After setting the device override, call driver.save_screenshot("mobile.png") to capture the emulated viewport.
  9. Clean up. Always call driver.quit() at the end to close the browser and release resources.

Common Mistakes

  • Using the wrong CDP command name. CDP commands are case-sensitive and follow a dotted notation (e.g., Emulation.setDeviceMetricsOverride). A typo will throw an error.
  • Forgetting to enable a domain. Some commands (like Network.enable) must be called before you can use related events or logs.
  • Mixing up parameter types. CDP expects specific JSON types—booleans must be True/False in Python, not strings.
  • Not waiting for the page to load. If you capture performance logs immediately after get(), some requests may not have finished. Use explicit waits or time.sleep() if needed.
  • Assuming CDP works on all browsers. CDP is Chrome-specific. For Firefox, you’d use the GeckoDriver’s own protocol, which is different.

Tips

  • Use Selenium 4+. The execute_cdp_cmd method is stable and doesn’t require a separate debugging port, making setup simpler.
  • Combine with Chrome options. You can set mobile emulation via ChromeOptions (e.g., mobile_emulation dict) instead of CDP, which is often easier for simple cases.
  • Check the CDP documentation. The official Chrome DevTools Protocol docs list all commands and their parameters—bookmark it for reference.
  • Use performance logs for testing. You can assert that certain resources load within a time limit, or that no 404 errors occur.
  • Handle interception carefully. If you block a critical resource, the page may break. Test with a whitelist approach first.

Troubleshooting

  • “Unknown command” error: Verify the command name is correct and that you’re using the right casing. Also ensure your ChromeDriver version is recent enough to support the command.
  • No performance logs returned: Make sure you enabled the Network domain before navigating. Also check that you’re reading logs after the page has fully loaded.
  • Device metrics not applied: If the screenshot looks like desktop, the override may have been reset. Some pages force a reload; re-apply the override after navigation.
  • ChromeDriver fails to start: Ensure ChromeDriver is in your PATH or specify its location explicitly. Also match the driver version to your Chrome browser version.
  • Interception not working: The interception event requires an event listener. In Selenium, this is tricky; consider using a library like selenium-wire for simpler request/response modification.

Frequently Asked Questions

Can I use CDP with Selenium Grid?

Yes, but only if the node runs Chrome and supports CDP. In Selenium 4, you can use driver.execute_cdp_cmd on a remote driver as long as the remote end supports it.

What is the difference between CDP and WebDriver?

WebDriver is a W3C standard for browser automation, while CDP is Chrome-specific and provides deeper access to browser internals like network, performance, and device emulation.

Can I use CDP to simulate slow network?

Yes, use Network.emulateNetworkConditions with parameters like offline, latency, and downloadThroughput.

Do I need a separate ChromeDriver for CDP?

No, the same ChromeDriver works. CDP commands are sent over the same connection.

Can I use CDP with Firefox?

No, CDP is Chrome-specific. Firefox has its own remote protocol (Marionette) but it doesn’t expose the same DevTools features.

Is CDP faster than regular Selenium?

For certain operations (like network interception), CDP can be more efficient because it avoids the overhead of WebDriver commands. However, for basic clicks and typing, the difference is negligible.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →