Capture All Requests With Selenium Wire in Headless Chrome
Capturing network requests in a headless browser environment allows developers and testers to inspect API calls, track XHR requests, and validate data transmission without the overhead of a visible browser window. Selenium Wire extends the standard Selenium WebDriver by integrating a built-in proxy server that intercepts all traffic between the browser and the internet, enabling you to access request and response headers, bodies, and status codes directly within your Python script.
What You'll Need
- Python 3.7 or higher installed on your system.
- The
selenium-wirelibrary (installed via pip). - Google Chrome browser installed.
- ChromeDriver, matching the version of your installed Chrome browser.
- Basic familiarity with Python scripting and the Selenium WebDriver API.
Step-by-Step
-
Install Dependencies: Begin by installing the necessary libraries. While standard Selenium is powerful, it cannot natively access the network layer. Install Selenium Wire using the command
pip install selenium-wire. This package includes everything needed to set up the internal proxy. Ensure your ChromeDriver is updated to match your current Chrome version to avoid session initialization errors. -
Import Required Modules: In your Python script, import the
webdriverfromseleniumwirerather than fromselenium. This is the most critical step; if you import from the standard selenium library, the proxy functionality will not be active, and therequestsattribute will be missing from your driver instance. -
Configure Chrome Options: To run the browser in headless mode, you must use the
Optionsclass fromselenium.webdriver.chrome.options. Add the--headlessargument to the options object. To ensure maximum compatibility and avoid detection or crashes in headless mode, it is highly recommended to also add--disable-gpuand--no-sandbox. The--window-sizeargument is also useful because some websites render different content or trigger different requests based on the perceived screen resolution. - Initialize the Driver with Selenium Wire: Create your driver instance by passing the options object. Selenium Wire automatically starts a local proxy server in the background and configures Chrome to route all traffic through it. You do not need to manually specify proxy settings in the Chrome options unless you are routing traffic through an external corporate proxy.
-
Navigate to the Target URL: Use
driver.get('your_url_here')to load the page. Once the page begins loading, Selenium Wire starts capturing every single request, including the initial HTML document, CSS files, JavaScript bundles, images, and asynchronous XHR/Fetch calls. -
Wait for Network Activity: Because headless browsers execute JavaScript asynchronously, you must ensure the requests you are looking for have actually been fired. Use
WebDriverWaitor a shorttime.sleep()to allow the page to fully initialize and trigger its API calls before attempting to read the request log. -
Access and Filter Requests: Use the
driver.requestslist to access all captured traffic. Since this list contains every single asset (including trackers and fonts), you will need to filter the results. Iterate through the list and check therequest.urlto find the specific API endpoint or resource you are targeting. -
Extract Request and Response Data: For each captured request, you can access
request.headers,request.body, andrequest.params. To see what the server sent back, access theresponseobject associated with the request, which providesresponse.status_codeandresponse.body. If the response body is compressed (e.g., Gzip), Selenium Wire typically handles the decompression automatically. -
Clean Up: Always call
driver.quit()at the end of your script. This not only closes the browser window but also shuts down the internal proxy server and releases the network ports used by Selenium Wire.
Common Mistakes
One of the most frequent errors is importing webdriver from selenium instead of seleniumwire. This results in an AttributeError: 'WebDriver' object has no attribute 'requests' because the standard Selenium driver does not track network traffic. Always verify your import statement at the top of the file.
Another common mistake is attempting to access request.response.body before the response has actually been received. In a fast-moving headless environment, the request object might exist in the list while the response is still pending. This can lead to NoneType` errors. Always check if request.response is not None before accessing its properties.
Users often forget to handle SSL certificates. Because Selenium Wire acts as a Man-in-the-Middle (MITM) proxy to intercept HTTPS traffic, it uses its own root certificate. While Selenium Wire usually handles this automatically for Chrome, some strict environments or specific website security policies may trigger SSL warnings. Ignoring these warnings via Chrome options is often necessary for headless stability.
Overlooking the --no-sandbox flag in Linux environments is a recurring issue. In many Docker containers or CI/CD pipelines, Chrome will fail to launch in headless mode without this flag due to permission restrictions on the namespace, leading to a session not created error.
Tips
To optimize performance, use driver.requests.clear() between different page navigations. If you are scraping a large site with hundreds of requests per page, the driver.requests list will grow indefinitely, consuming significant RAM and slowing down the filtering process. Clearing the log ensures you only analyze the requests from the current action.
For more precise filtering, use regular expressions (the re module) to match URLs. Instead of checking if a string is exactly equal to a URL, check if the URL contains a specific keyword or matches a pattern. This is essential for dealing with dynamic query parameters or versioned API endpoints (e.g., /api/v1/ vs /api/v2/).
If you need to modify requests on the fly—such as changing a User-Agent or adding a custom header to every single request—use the seleniumwire.interceptors feature. This allows you to define a function that intercepts every request before it leaves the browser, enabling you to spoof device types or bypass simple bot detection mechanisms.
To save bandwidth and speed up headless execution, you can use Selenium Wire to block unnecessary requests. By intercepting requests for images, CSS, or tracking scripts and returning a 404 or an empty response, you can significantly reduce the page load time and focus only on the data-rich XHR requests.
Troubleshooting
If the browser fails to launch or hangs at the start, check if there is a port conflict. Selenium Wire uses a default port for its proxy; if another application is using that port, the driver will not initialize. You can specify a custom port in the seleniumwire_options dictionary when initializing the driver.
If you see empty response bodies for HTTPS requests, ensure that you haven't disabled the proxy in your Chrome options. Some users accidentally add --proxy-server='direct://'` to their options, which tells Chrome to bypass all proxies, effectively blinding Selenium Wire to the traffic.
When encountering WebDriverException: Message: session not created: This version of ChromeDriver only supports Chrome version X, you must update your driver. The easiest way to handle this in Python is by using the webdriver-manager library, which automatically detects your Chrome version and downloads the corresponding driver binary.
If you are running this in a headless environment and the page content seems different from the headed version, try setting a realistic User-Agent. Many servers detect the default headless Chrome User-Agent (which often contains the word "Headless") and serve a simplified page or a CAPTCHA. Use options.add_argument('user-agent=...') with a real browser string to mimic a human user.
Frequently Asked Questions
Does Selenium Wire slow down the browser?
Yes, there is a slight performance overhead because all traffic is routed through a local proxy server. However, for most automation tasks, this latency is negligible compared to the time spent waiting for page renders.
Can I capture WebSockets with Selenium Wire?
Selenium Wire is primarily designed for HTTP/HTTPS requests. While it can capture the initial WebSocket handshake (the HTTP request that upgrades the connection), it does not capture the subsequent binary frames sent over the established WebSocket connection.
Is Selenium Wire compatible with Firefox?
Yes, Selenium Wire supports Firefox as well. You simply need to use seleniumwire.firefox.webdriver and the corresponding geckodriver` binary.
Do I need to install a separate proxy server?
No, Selenium Wire includes its own lightweight proxy server that is automatically started and stopped along with the WebDriver session.
How do I handle sites with strict SSL pinning?
Sites with strict SSL pinning may detect the MITM proxy and refuse to connect. In these cases, you may need to use more advanced tools like Playwright or Puppeteer, or attempt to inject the Selenium Wire root certificate into the system's trusted store.
Can I capture requests from iframes?
Yes, because the proxy operates at the network level, it captures all requests made by the browser regardless of whether they originate from the main document or an embedded iframe.